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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
| #include <stdio.h>
int binary_search_iterative(int arr[], int size, int target) { int left = 0; int right = size - 1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] > target) { right = mid - 1; } else { left = mid + 1; } } return -1; }
int binary_search_recursive(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 binary_search_recursive(arr, left, mid - 1, target); } else { return binary_search_recursive(arr, mid + 1, right, target); } }
int binary_search_lower_bound(int arr[], int size, int target) { int left = 0; int right = size; while (left < right) { int mid = left + (right - left) / 2; if (arr[mid] < target) { left = mid + 1; } else { right = mid; } } return left; }
int binary_search_upper_bound(int arr[], int size, int target) { int left = 0; int right = size; while (left < right) { int mid = left + (right - left) / 2; if (arr[mid] <= target) { left = mid + 1; } else { right = mid; } } return left; }
void test_binary_search() { int arr[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}; int size = sizeof(arr) / sizeof(arr[0]); printf("数组: "); for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n\n"); int targets[] = {7, 12, 1, 19, 20}; int num_targets = sizeof(targets) / sizeof(targets[0]); for (int i = 0; i < num_targets; i++) { int target = targets[i]; int result1 = binary_search_iterative(arr, size, target); int result2 = binary_search_recursive(arr, 0, size - 1, target); printf("查找 %d:\n", target); printf(" 迭代版本: %s\n", result1 != -1 ? "找到" : "未找到"); printf(" 递归版本: %s\n", result2 != -1 ? "找到" : "未找到"); if (result1 != -1) { printf(" 位置: %d, 值: %d\n", result1, arr[result1]); } printf("\n"); } printf("边界查找测试:\n"); for (int i = 0; i < num_targets; i++) { int target = targets[i]; int lower = binary_search_lower_bound(arr, size, target); int upper = binary_search_upper_bound(arr, size, target); printf("目标 %d: lower_bound=%d, upper_bound=%d\n", target, lower, upper); } }
int main() { printf("=== 二分查找算法演示 ===\n\n"); test_binary_search(); return 0; }
|