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生成随机大数据文件
    spark读hdfs文件实现wordcount并将结果存回hdfs
    spark streaming 实现接收网络传输数据进行WordCount功能
    spark mllib k-means算法实现
    java实现读取文件大全
    spark+hcatalog操作hive表及其数据
    在hdfs上存取xml文件的实现代码
    hadoop shell 详解
    day 01 预科
    c盘没有新建修改权限的,执行下面命令
  • 原文地址:https://www.cnblogs.com/jiangu66/p/3061701.html
Copyright © 2011-2022 走看看