二分法查找-C语言

已排序的整数数组arr为:[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37]。

请用二分法查找35 和 20,分别给出它们在数组种的位置。

二分法查找(Binary Search)是一种在已排序数组中查找特定元素的搜索算法。它通过不断将数组分为两半来缩小搜索范围,直到找到所需的元素或确定元素不存在。

以下是二分法查找的基本步骤:

确定数组的最低索引(low)和最高索引(high),初始时通常是数组的第一个元素和最后一个元素。

计算中间索引(mid)作为low和high的平均值,即 mid = (low + high) / 2。

比较中间索引处的元素与目标值:

如果中间索引处的元素等于目标值,则搜索成功,返回中间索引。

如果中间索引处的元素小于目标值,则将最低索引更新为mid + 1,因为目标值必定在中间索引的右侧。

如果中间索引处的元素大于目标值,则将最高索引更新为mid - 1,因为目标值必定在中间索引的左侧。

重复步骤2和3,直到找到目标值或者最低索引大于最高索引(这意味着目标值不存在于数组中)。

#include <stdio.h>  
  
int binarySearch(int arr[], int low, int high, int target) {  
    if (high >= low) {  
        int mid = low + (high - low) / 2;  
  
        if (arr[mid] == target) {  
            return mid;  
        }  
  
        if (arr[mid] > target) {  
            return binarySearch(arr, low, mid - 1, target);  
        }  
   
        return binarySearch(arr, mid + 1, high, target);  
    }  
  
    return -1;  
}  
  
int main() {  
    int arr[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37};  
    int n = sizeof(arr) / sizeof(arr[0]);  
  
    int target1 = 35;  
    int target2 = 20;  
  
    int result1 = binarySearch(arr, 0, n - 1, target1);  
    int result2 = binarySearch(arr, 0, n - 1, target2);  
  
    if (result1 != -1) {  
        printf("Element %d is found at index %d\n", target1, result1);  
    } else {  
        printf("Element %d is not found in the array\n", target1);  
    }  
  
    if (result2 != -1) {  
        printf("Element %d is found at index %d\n", target2, result2);  
    } else {  
        printf("Element %d is not found in the array\n", target2);  
    }  
  
    return 0;  
}

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值