C语言排序之折半查找代码实现
- #include <stdio.h>
- int searchItem(int key ,int arr[] ,int len){//分别是需要找的数,定义一个数组形参,在main中计算出的元素个数
-
- int low =0 ,high = len -1 , mid ;
-
- while (low <= high ) {
- mid =(low+high)/2;
- if (key > arr[mid]) {
- low = mid+1;
- }
- else if(key <arr[mid]){
- high = mid -1;
-
- }
- else
- {
- return mid;
- }
-
- }
- return -1 ;
- }
- int main(int argc, const char * argv[]) {
- int a[]={1, 2 ,3 ,12 ,20 ,30 ,32, 34, 39, 76 ,99 };
- int len = sizeof(a)/sizeof(int);
- int result = searchItem(32,a,len);
-
- if (result != -1) {
- printf("a[%d] = %d \n",result,a[result]);
- }
- else {
- printf(" 未找到! \n");
- }
- printf("\n");
-
- return 0;
- }
复制代码
|
|