二分查找(折半查找)
1,非递归方式:
1 #include<stdio.h> 2 #include<stdlib.h> 3 4 int BinarySearch(int arr[], int arrlen, int targetVal) { 5 //int arrlen = sizeof(arr) / sizeof(arr[0]); 6 //printf("arrlen:%d\n", arrlen); 1 ??? 7 int mid_index = (0 + arrlen - 1) / 2; 8 int left_index = 0; 9 int right_index = arrlen - 1; 10 if (left_index > right_index) { //没有找到的情况 11 return -1; 12 } 13 //1,目标值比中间值小,在数组左边找 14 else if (arr[mid_index] > targetVal) { 15 for (int i = 0; i <= mid_index; i++) { 16 if (arr[i] == targetVal) { 17 return i; 18 } 19 } 20 return -1; 21 } 22 //2,目标值比中间值大,在数组右边找 23 else if (arr[mid_index] < targetVal) { 24 for (int i = mid_index; i <= right_index; i++) { 25 if (arr[i] == targetVal) { 26 return i; 27 } 28 } 29 return -1; 30 } 31 //3,数组的中间值等于目标值,找到了,直接返回中间值下标 32 else { 33 return mid_index; 34 } 35 } 36 37 void main() { 38 int arr[] = {61,87,170,275,426,503,512,653,897,908}; 39 int num = 0; 40 printf("初始数组是:\n"); 41 int arrlen = sizeof(arr) / sizeof(int); 42 //printf("%d\n", arrlen); //10 43 for (int i = 0; i < arrlen; i++) { 44 printf("%d ", arr[i]); 45 } 46 printf("\n"); 47 48 49 printf("请输入你想找的数字:"); 50 scanf("%d", &num); 51 int res = BinarySearch(arr,arrlen, num); 52 if (res != -1) { 53 printf("找到了,下标是%d\n", res); 54 } 55 else { 56 printf("没有找到"); 57 } 58 59 }
数组长度 arrlen 在 查找方法内计算 不正确,但是 在 main 中计算正确,(?)
因此,直接使用了直接传参的方式,将 arrlen 传入到 BinarySearch( ) 中
2,递归方式:
1 //二分查找,递归 2 #include<stdio.h> 3 #include<stdlib.h> 4 5 int BinarySearch(int arr[],int left_index, int right_index, int targetVal) { 6 int mid_index = (left_index + right_index) / 2; 7 if (left_index > right_index) { //没有找到的情况 8 return -1; 9 } 10 //1,目标值比中间值小,在数组左边找 11 else if (arr[mid_index] > targetVal) { 12 BinarySearch(arr,left_index, mid_index - 1, targetVal); 13 } 14 //2,目标值比中间值大,在数组右边找 15 else if (arr[mid_index] < targetVal) { 16 BinarySearch(arr,mid_index+1, right_index, targetVal); 17 } 18 //3,数组的中间值等于目标值,找到了,直接返回中间值下标 19 else { 20 return mid_index; 21 } 22 } 23 24 void main() { 25 int arr[] = {61,87,170,275,426,503,512,653,897,908}; 26 int num = 0; 27 printf("初始数组是:\n"); 28 int arrlen = sizeof(arr) / sizeof(int); 29 //printf("%d\n", arrlen); //10 30 for (int i = 0; i < arrlen; i++) { 31 printf("%d ", arr[i]); 32 } 33 printf("\n"); 34 35 printf("请输入你想找的数字:"); 36 scanf("%d", &num); 37 int res = BinarySearch(arr,0,arrlen-1, num); 38 if (res != -1) { 39 printf("找到了,下标是%d\n", res); 40 } 41 else { 42 printf("没有找到"); 43 } 44 45 }