折半查找(二进制搜索)

二进制搜索:通过将搜索间隔重复划分一半来搜索排序的数组。从覆盖整个阵列的间隔开始。如果搜索键的值小于间隔中间的项,则将间隔缩小到下半部。否则将其缩小到上半部。重复检查,直到找到值或间隔为空。

二进制搜索的想法是使用数组排序的信息,并将时间复杂度减少到O(Logn)。

在一次比较之后,我们基本上忽略了一半的元素。

  1. 将x与中间元素进行比较。
  2. 如果x与中间元素匹配,则返回中间索引。
  3. 否则如果x大于中间元素,则x只能在中间元素之后位于右半子阵列中。所以我们再次出现在右边。
  4. 其他(x较小)再次出现在左半边。

 递归执行代码如下:

#include <stdio.h>
 
// A recursive binary search function. It returns location of x in given array arr[l..r] is present, otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
   if (r >= l)
   {
        int mid = l + (r - l)/2;
 
        // If the element is present at the middle itself
        if (arr[mid] == x)  return mid;
 
        // If element is smaller than mid, then it can only be present
        // in left subarray
        if (arr[mid] > x) return binarySearch(arr, l, mid-1, x);
 
        // Else the element can only be present in right subarray
        return binarySearch(arr, mid+1, r, x);
   }
 
   // We reach here when element is not present in array
   return -1;
}
 
int main(void)
{
   int arr[] = {2, 3, 4, 10, 40};
   int n = sizeof(arr)/ sizeof(arr[0]);
   int x = 10;
   int result = binarySearch(arr, 0, n-1, x);
   (result == -1)? printf("Element is not present in array")
                 : printf("Element is present at index %d", result);
   return 0;
}

  

下面是非递归的C++代码,如下:

#include <iostream>
using namespace std;

int main()
{
    int Arr[10]={12,23,25,34,36,37,44,48,67,89};
    int l=0,r=9,m,x,index=-1;
    cin>>x;
    while(l<=r)
    {
        m=(l+r)/2;
        if(Arr[m]>x)
        {
            r=m-1;
        }
        else if(Arr[m]==x)
        {
            index=m;
            break;
        }
        else
        {
            l=m+1;
        }
    }
    cout<<index<<endl;
    return 0;
}

  

转载于:https://www.cnblogs.com/wongyi/p/7729103.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值