基本思想:二分法的一个前提是序列已经是有序的,然后将待查找值与序列的中点比较。根据比较结果,选择下一步比较的部分。二分查找(binary search)就是一个不断重复这一查找过程,直到找到这个值。

算法复杂度:O(lgn)

算法实现:

一:迭代法

int bin_search_iteration(int arr[],int start,int end,int x)
{


    
    while (start<end)
    {
        int mid = (start + end) / 2;
        if (arr[mid]<x)
        {
            start = mid + 1;
        }
        else if (arr[mid]==x)
        {
            return mid;
        }
        else
        {
            end = mid - 1;
        }
    }
    if (start == end)
        return arr[start] == x ? start : -1;
    else
    {
        return -1;
    }


}

二:递归法

int  bin_search(int arr[],int start,int end,int x)
{
    if (start == end)
        return arr[start]==x?start:-1;
    
    int mid = (start+end) / 2;
    if(arr[mid]==x)
    {
        return mid;
    }
    else if(arr[mid]>x)
    {
        return bin_search(arr, start,mid, x);
    }
    else
    {
        return bin_search(arr, mid+1,end, x);
    }

    
}

 

相关文章:

  • 2023-01-13
  • 2021-12-06
  • 2023-02-03
  • 2021-07-07
  • 2021-08-27
  • 2021-12-15
  • 2022-12-23
猜你喜欢
  • 2022-02-17
  • 2022-12-23
  • 2022-01-12
  • 2021-10-09
  • 2021-08-22
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案