输入一个有序的数组,查找key=10的mid值
- int zheban(int a[], int len,int key){
- //先定义变量
- int low = 0, high = len - 1, mid;
- //循环
- while (low <= high)
- {
- //计算mid是位置
- mid = (low+high)/2;
- //key>a[mid] low=mid+1; key<a[mid] high=mid-1; key>a[mid] return mid;
- if (key > a[mid]){ low = mid + 1; }
- else if (key<a[mid])
- {
- high = mid - 1;
- }
- else
- {
- return mid;
- }
-
- }
- return -1;
- }
- int main(int argc, char *argv[])
- {
-
- int a[8] = { 3, 4, 10, 58, 69, 78, 85, 92 };
- int s= zheban(a, 8,10);//把数已经排序完
- printf("%d ", s);
- return 0;
- }
复制代码 |
|