利用快速排序和二分查找数字出现次数

本文介绍了一种使用快速排序算法进行数组排序的方法,并结合二分查找实现对特定元素出现次数的统计。通过随机初始化数组并展示排序过程,最终实现了对指定数值在数组中出现频率的高效查找。

 

 

#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;
}

 

 

 

转载于:https://www.cnblogs.com/jiangu66/archive/2013/05/05/3061701.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值