您的位置:首页 > 其它

C 语言经典题目系列解决方案(11)-折半查找

2010-09-17 08:46 387 查看
直接给出代码:
main(){
	int i,n=10;
	int numbers[10];
	int searchValue,returnValue;
	int partition(int a[],int low,int high);
	void quickSort(int a[],int low,int high);
	int  binarySearch(int a[],int low,int high,int key);
	
	//生成数组
	for (i=0;i<n;i++){
        numbers[i]=(int)rand()%100;
		printf("%3d",numbers[i]);
		if (i==n-1) printf("/n");
	}
     
	quickSort(numbers,0,n-1); // 使之有序

	for (i=0;i<n;i++){
		printf("%3d",numbers[i]);
		if (i==n-1) printf("/n");
	}

	printf("which value do you want to search:");
	scanf("%d",&searchValue);
    // 折半查找
    returnValue=binarySearch(numbers,0,n-1,searchValue);
    if (returnValue==-1) printf("不存在该序列中/n");
    else printf("索引为:%d/n",returnValue);
	
	getchar();
}

//一趟快排
int partition(int a[],int low,int high){
    int pivotValue;
    pivotValue=a[low];
	while(low<high){
		while(lowpivotValue)  high--;//找第一个小于“枢纽值”的,向前挪
		a[low]=a[high];
		while(low<high && a[low]<pivotValue) low++;//找第一个大于“枢纽值”的,向后挪
		a[high]=a[low];
	}
    a[low]=pivotValue;
	return low;
}

//递归快排
void quickSort(int a[],int low,int high){
     int pivotLoc;
	 if (low<high) // 长度大于1时执行。
	 {
		 pivotLoc=partition(a,low,high);
		 quickSort(a,low,pivotLoc-1);
		 quickSort(a,pivotLoc+1,high);
	 }
}

//折半查找
int  binarySearch(int a[],int low,int high,int key){
	 int mid;
	 while(low<=high)
	 {
	   mid=(int)(low+high)/2;
	   if (a[mid]==key)  return mid;
	   if  (a[mid]>key)  high=mid-1;
	   else low=mid+1;
	 }
	 return -1;
 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: