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; }
相关文章推荐
- C 语言经典题目系列解决方案(10)-快排
- C 语言经典题目系列解决方案(1)-报数问题
- C 语言经典题目系列解决方案(4)-Fibonacci
- C 语言经典题目系列解决方案(7)-冒泡排序
- C 语言经典题目系列解决方案(9)-直接插入排序
- C 语言经典题目系列解决方案(8)-选择排序
- C 语言经典题目系列解决方案(5)-gcd问题
- C 语言经典题目系列解决方案(6)-有序链表的归并
- C 语言经典题目系列解决方案(3)-链表创建与倒置
- C语言经典题目系列解决方案(2)-统计字符
- 计算机等级考试二级C语言超级经典400道题目(3)
- C 语言的一些经典题目
- C语言经典题目(41-50)
- Netty 快速入门系列 - Chapter 7 数据包协议【第十八讲】解决方案-经典协议包结构
- 计算机等级考试二级C语言超级经典400道题目(4)
- C语言超级经典400道题目
- C语言经典题目(11-20)
- C语言经典题目(51-60)
- 计算机等级考试二级C语言超级经典400道题目(5)
- C 语言经典题目