c语言

c语言折半查找代码怎么写

小亿
97
2023-11-28 13:35:56
栏目: 编程语言

以下是一个使用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;
        }
        
        if (arr[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    
    // 当查找不到目标元素时,返回-1表示查找失败
    return -1;
}

int main() {
    int arr[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
    int target = 30;
    int size = sizeof(arr) / sizeof(arr[0]);
    
    int result = binarySearch(arr, 0, size - 1, target);
    if (result == -1) {
        printf("目标元素 %d 未找到\n", target);
    } else {
        printf("目标元素 %d 在数组中的索引为 %d\n", target, result);
    }
    
    return 0;
}

运行以上代码,将输出 “目标元素 30 在数组中的索引为 5”,表示目标元素30在数组中的索引位置为5。如果目标元素不在数组中,则输出 “目标元素 30 未找到”。

0
看了该问题的人还看了