Binary Search in C: Find Numbers Fast
Below is an example code that beautifully implements using the binary search method in the C programming language to find a number.
#include <stdio.h>
int binarySearch(int arr[], int n, int target) {
int left = 0;
int 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; // 返回-1表示未找到目标数
}
int main() {
int arr[] = {2, 4, 6, 8, 10, 12, 14, 16, 18};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 10;
int result = binarySearch(arr, n, target);
if (result != -1) {
printf("目标数 %d 找到在索引 %d\n", target, result);
} else {
printf("目标数 %d 未找到\n", target);
}
return 0;
}
You can pass the array and the target number to the binarySearch function and find the target number at the index position returned by the function. If the target number is not found, the function will return -1. In the example above, the target number 10 was found at index 3 in the array.