代码:
1 int sequenceSearchV0(int *arr, int value, int size){ 2 for(int i = 0; i < size; i++){ 3 if(*(arr + i) == value){ 4 return i; 5 } 6 } 7 return -1; 8 } 9 10 int sequenceSearchV1(int *arr, int value, int size){ 11 int tmp = -1; 12 for(int i = 0; i < size; i++){ 13 if(*(arr + i) == value){ 14 tmp = i; 15 } 16 } 17 return tmp; 18 } 19 20 int sequenceSearchV2(int arr[], int value){ 21 int size = sizeof(arr)/sizeof(arr[0]); 22 int tmp = -1; 23 for(int i = 0; i < size; i++){ 24 if(*(arr + i) == value){ 25 tmp = i; 26 } 27 } 28 return tmp; 29 } 30 31 int binarySearch(int arr[], int valule){ 32 int tmp = -1; 33 int size = sizeof(arr)/sizeof(arr[0]);//11 34 int low = 0; 35 int high = size - 1; 36 int mid = 0; 37 while(low <= high){ 38 mid = (low + high)/2 39 if(arr[mid] == value){ 40 tmp = mid; 41 } 42 if(arr[mid] > value){ 43 high = mid - 1; 44 } 45 if(arr[mid] < value){ 46 low = mid + 1; 47 } 48 } 49 return tmp; 50 } 51 int main(int argc, char **argv) 52 { 53 int arr[] = {0,16,24,35, 44, 47,59,62,73,88,99}; 54 int key=100; 55 int index=binarySearch(arr,key); 56 printf("%d is located at: %d ", key, index); 57 return 0; 58 }