1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| #include <stdio.h> int erfeng(int *arr,int target,int left,int right){ int mid = (left + right) / 2; if (left>right) { return -1; } if (target>arr[mid]) { left =mid; return erfeng(arr,target,left+1,right); } else if (target < arr[mid]) { right = mid; return erfeng(arr,target,left,right-1); } else{ return mid; }
} int main(int argc, char const *argv[]) { int arr[11] = {1,4,8,9,12,14,22,30,39,55,57}; int target; int loc; int left = 0, right = 11; scanf("%d",&target); loc=erfeng(arr,target,left,right); printf("%d",loc); return 0; }
|