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

   2025-02-15 3960
核心提示:以下是一个使用C语言编写的折半查找算法的示例代码:#include stdio.hint binarySearch(int arr[], int left, int right, int ta

以下是一个使用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 未找到”。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言