二进制树型搜索算法_二进制搜索算法

二进制搜索应用于已排序的数组或大型列表,其时间复杂度为O(log n)。该算法从中间元素开始,根据目标值与中间元素的比较结果决定向左还是向右子区间搜索。如果数组未排序,二进制搜索无法工作。通过理解对数的性质,可以计算出在给定元素数量下搜索所需的步数。
摘要由CSDN通过智能技术生成

二进制树型搜索算法

Binary Search is applied on the sorted array or list of large size. It's time complexity of O(log n) makes it very fast as compared to other sorting algorithms. The only limitation is that the array or list of elements must be sorted for the binary search algorithm to work on it.

二进制搜索应用于排序后的数组或大型列表。 O(log n)的时间复杂性使其与其他排序算法相比非常快。 唯一的限制是必须对元素的数组或列表进行排序,以便二进制搜索算法可以对其进行处理。

实现二进制搜索算法 (Implementing Binary Search Algorithm)

Following are the steps of implementation that we will be following:

以下是我们将要执行的实现步骤:

  1. Start with the middle element:

    从中间元素开始:

    • target value is equal to the middle element of the array, then return the index of the middle element.目标值等于数组的中间元素,则返回中间元素的索引。
      • If the target value is greater than the number in the middle index, then pick the elements to the right of the middle index, and start with Step 1.
      • If the target value is less than the number in the middle index, then pick the elements to the left of the middle index, and start with Step 1.
  2. When a match is found, return the index of the element matched.

    找到匹配项后,返回匹配元素的索引。

  3. If no match is found, then return -1

    如果找不到匹配项,则返回-1

/*
    function for carrying out binary search on given array
    - values[] => given sorted array
    - len => length of the array
    - target => value to be searched
*/
int binarySearch(int values[], int len, int target)
{
    int max = (len - 1);
    int min = 0;
    
    int guess;  // this will hold the index o
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值