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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| #include <stdio.h>
int binarySearchIterative(int arr[], int n, int target) { int left = 0, right = n - 1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return -1; }
int binarySearchRecursive(int arr[], int left, int right, int target) { if (left > right) { return -1; } int mid = left + (right - left) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { return binarySearchRecursive(arr, mid + 1, right, target); } else { return binarySearchRecursive(arr, left, mid - 1, target); } }
int findFirst(int arr[], int n, int target) { int left = 0, right = n - 1; int result = -1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) { result = mid; right = mid - 1; } else if (arr[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return result; }
void binarySearchTest() { printf("\n=== 二分查找 ===\n"); int arr[] = {1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9}; int n = sizeof(arr) / sizeof(arr[0]); int target = 5; printf("数组:"); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); int pos1 = binarySearchIterative(arr, n, target); int pos2 = binarySearchRecursive(arr, 0, n - 1, target); int first_pos = findFirst(arr, n, target); printf("查找目标:%d\n", target); printf("迭代查找位置:%d\n", pos1); printf("递归查找位置:%d\n", pos2); printf("第一次出现位置:%d\n", first_pos); }
|