折半查找:
- #include <stdio.h>
- /*
- * 使用折半查找来查找一个数
- *
- * @param arr 数组
- * @param len 数组长度
- * @param key 要查找的数 20
- *
- * @return 要查找的数的位置,如果查找不到返回值 -1
- */
- int searchItem(int arr[],int len, int key){
- //先要定义变量
- int low=0, high=len-1,mid;
-
- //循环
-
- while (low<=high) {
-
-
- //计算mid 位置
- mid =(low+high)/2;
-
- //判断 key和a[mid],右半区查找
- if (key > arr[mid]) {
-
-
- //key> arr[mid] low= mid+1;
- low= mid+1;
- }else if (key < arr[mid]){
-
- //key< arr[mid]; high= mid-1;
- high= mid-1;
-
- }else{
-
- //key == arr[mid]; //return mid;
- return mid;
- }
-
- }
- //查找不到的情况
- return -1;
-
- }
- int main(int argc, const char * argv[]) {
-
- //定义一个数组
-
- int a[]={3,4,12,20,21,23,28,45,67,100};
-
- //查找的 key=20
-
- int loc = searchItem(a, 10, 20);
-
- printf("loc = %d\n",loc); // loc = 3;
-
-
- return 0;
- }
复制代码
|
|