二分查找是只适用于有序的序列,每次都缩小一半查找范围的查找方法。
二分查找也叫做折半查找。
步骤:
首先,假设表中元素是按升序排列,将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置将表分成前后两个子表。
重复以上步骤。
1 #include<stdio.h> 2 #include<stdlib.h> 3 4 int binarysearch(int *array,int key,int low,int high) 5 { 6 int mid; 7 while(low<=high) 8 { 9 mid = (low + high)/2; 10 if(key == array[mid]) 11 return mid; 12 else if(key<array[mid]) 13 high = mid-1; 14 else 15 low = mid+1; 16 } 17 return 0; 18 } 19 int main() 20 { 21 int n,i,key,position; 22 int *array; 23 printf("input size of array: "); 24 scanf("%d",&n); 25 array = (int*)malloc(sizeof(int)*n); 26 printf("input data as asc"); 27 for(i=0;i<n;i++) 28 scanf("%d",&array[i]); 29 printf("input what you want: "); 30 scanf("%d",&key); 31 if(position = binarysearch(array,key,0,n-1)) 32 printf("the position of %d is %d ",key,position); 33 else 34 printf("no exist %d",key); 35 return 0; 36 }