zoukankan      html  css  js  c++  java
  • 利用快速排序和二分查找数字出现次数

     

     

    #include <windows.h>
    #include <stdlib.h> 
    #include <stdio.h> 
    #include <time.h>
    #include <ctime>
    #include <algorithm> 
    #define ARRLEN 1000
    using namespace std;
    
    int arr[ARRLEN];
    
    int Patition(int arr3[], int low, int high)
    {
    
    	int pivotkey=arr3[low];
    	int temp = arr3[low];
    
    	while(low<high)
    	{
    
    		while(low <high && arr3[high]>=pivotkey)
    		{
    			--high;;
    		}
    		arr3[low]=arr3[high];
    		while(low<high && arr3[low]<=pivotkey)
    		{
    			++low;;
    		}
    		arr3[high]=arr3[low];
    	}
    	arr3[low] = temp;
    	return low;
    
    }
    void QuickSort(int arr3[], int low, int high)
    {
    	if(low<high)
    	{
    		int pivotloc=Patition(arr3,low, high);
    		QuickSort(arr3, low, pivotloc-1);
    		QuickSort(arr3, pivotloc+1, high);
    	}
    }
    int BinarySearch(int arr[],int start,int end,int key){
    	if (arr[start]==key)
    		return start;
    	if (arr[end]==key)
    		return end;
    
    	while(start<end){
    		int mid=(start+end)/2;
    		if (arr[mid]==key){
    			return mid;
    		}
    		if (arr[mid]>key)
    			end=mid-1;
    		else
    			start=mid+1;
    	}
    	if(start>=end)
    		return -1;
    }
    int SearchTheTimesOfK(int arr[],int start,int end,int key){
    	int index=BinarySearch(arr,0,ARRLEN-1,key);
    	if(index==-1)return index;
    
    	int firstindex=index,lastindex=index;
    	while (firstindex>=0&&arr[firstindex]==key)
    		firstindex--;
    	while(lastindex<ARRLEN&&arr[lastindex]==key)
    		lastindex++;
    
    	return lastindex-firstindex-1;
    }
    void InitArr(){
    	for (int i=0,j;i<ARRLEN;i++)
    	{
    		j=rand()%1000;
    		arr[i]=j;
    	}
    }
    void Display(int arr[],int n){
    	int i=0;
    	while(n--){
    		printf("%d ",arr[i]);
    		i++;
    	}
    }
    int main(void){
    	InitArr();
    	QuickSort(arr,0,ARRLEN-1);
    	Display(arr,ARRLEN);
    	printf("\n");
    	int times=SearchTheTimesOfK(arr,0,ARRLEN-1,999);
    	if (times!=-1)
    	   printf("%d",times);
    	else
    		printf("找不到!");
    	getchar();
    	return 0;
    }

     

     

     

  • 相关阅读:
    Java导出Excel和CSV(简单Demo)
    ffmepg命令行参数
    VLC命令参数(转载)
    深入Java虚拟机读书笔记第五章Java虚拟机
    JS常用方法记录
    记一次数据库的优化
    Infobright数据库使用
    Mysql连接驱动8.0版本改动
    Eclipse新建SrpingBoot项目Pom.xml文件报错
    SpringBoot 热部署开发
  • 原文地址:https://www.cnblogs.com/jiangu66/p/3061701.html
Copyright © 2011-2022 走看看