折半查找也称为二分查找,它要求被查找的数组是有序的。
实现折半查找算法可以按照以下步骤:
下面是一个示例代码:
#include <stdio.h>
int binarySearch(int arr[], int target, int start, int end) {
    while (start <= end) {
        int mid = start + (end - start) / 2;
        
        if (arr[mid] == target) {
            return mid;
        } else if (arr[mid] > target) {
            end = mid - 1;
        } else {
            start = mid + 1;
        }
    }
    
    return -1;
}
int main() {
    int arr[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
    int target = 12;
    int n = sizeof(arr) / sizeof(arr[0]);
    int result = binarySearch(arr, target, 0, n - 1);
    
    if (result == -1) {
        printf("Element not found\n");
    } else {
        printf("Element found at index %d\n", result);
    }
    
    return 0;
}
以上代码在一个有序数组中查找目标元素12,并输出其索引。如果目标元素存在于数组中,则输出对应索引;否则输出"Element not found"。