赞
踩
- #include<stdio.h>
- int two_search(int arr[], int length, int k)
- {
- int left = 0;
- int right = length - 1;
-
- while (left <= right)
- {
- int mid = (right + left) / 2; //(0+9)/2=4
- if (k > arr[mid])
- left = mid+1; //加1 减1 是必须的
- else if (k < arr[mid])
- right = mid-1;
- else
- return mid;
- }
- return -1;
- }
-
- int main()
- {
- int arr[] = {1,2,3,4,5,6,7,8,9,10};
- int k = 11; //想查找的数的下标
-
- int length = sizeof(arr) / sizeof(arr[0]);
- int ret = two_search(arr,length,k);
- if (ret != -1)
- printf("找到,%d在数组中的下标为%d", k, ret);
- else
- printf("未找到");
- return 0;
- }
- while (left <= right)
- {
- int mid = (right + left) / 2; //(0+9)/2=4
- if (k > arr[mid])
- left = mid+1; //加1 减1 是必须的
- else if (k < arr[mid])
- right = mid-1;
- else
- return mid;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。