温馨提示×

C语言折半查找算法的代码怎么写

小亿
93
2024-03-12 18:08:41
栏目: 编程语言

下面是一个基本的C语言折半查找算法的示例代码:

#include <stdio.h>

int binarySearch(int arr[], int left, int right, int target) {
    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 main() {
    int arr[] = {1, 3, 5, 7, 9, 11, 13, 15};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 7;
    
    int result = binarySearch(arr, 0, n - 1, target);
    
    if (result == -1) {
        printf("Element not found\n");
    } else {
        printf("Element found at index %d\n", result);
    }
    
    return 0;
}

在这个示例代码中,binarySearch函数接受一个已排序的数组、数组的左边界、右边界和目标元素作为参数,并返回目标元素的索引。在main函数中,我们声明一个已排序的数组arr,然后调用binarySearch函数来查找目标元素7。如果找到目标元素,则打印出目标元素的索引,否则打印出“Element not found”。

0