精华内容
下载资源
问答
  • 二进制搜索算法by Julia Geist Julia·盖斯特(Julia Geist) 使用安全摄像机镜头解释二进制搜索算法 (Binary Search Algorithms explained using security camera footage) Binary search, also known as half-...

    二进制搜索算法

    by Julia Geist

    Julia·盖斯特(Julia Geist)

    使用安全摄像机镜头解释二进制搜索算法 (Binary Search Algorithms explained using security camera footage)

    Binary search, also known as half-interval search or logarithmic search, is a search algorithm that finds the position of a target value within a sorted array.
    二进制搜索(也称为半间隔搜索或对数搜索)是一种搜索算法,用于查找排序数组中目标值的位置。

    语境 (Context)

    I used to live in a building that had a communal kitchen for over 100 students. As you might imagine, there were almost always dishes that weren’t washed in the sink. A group at my school pitched the idea to put up a Nest Cam to catch culprits and call them out on it using the Nest Cam feed.

    我曾经住在一栋有公用厨房的大楼里,可容纳100多名学生。 就像您想象的那样,几乎总是有没有在水槽中洗过的盘子。 我学校的一个小组提出了创建一个Nest Cam来捕捉罪犯的想法,并使用Nest Cam feed将其召唤出来。

    To illustrate my point, let’s say you found dirty dishes at 12 pm, and you hadn’t been in the kitchen for a day.

    为了说明我的观点,假设您在中午12点发现了脏盘子,而您一天都没有在厨房里。

    Think about the way that you would search for the person who left the dishes. Would you watch all 24 hours of footage, from the beginning, until you found the culprit?

    考虑一下您寻找离开盘子的人的方式。 从头开始,直到发现罪魁祸首,您是否会观看所有24小时的录像?

    Probably not. Most likely you’d be hopping around the footage, checking to see if the dishes were in the sink, say, 12 hours ago — at 12 am. If they were, then you’d know that it happened before 12 am. You might flip back to 10 pm after that. If the dishes aren’t there, you’ve now narrowed down the time frame from 10 pm to 12 am — in other words, you’ve ruled out any time before 10 pm. You’d continue this process until you found the culprit.

    可能不是。 例如,您很可能会在画面上跳来跳去,例如12个小时前的凌晨12点,检查盘子是否在水池中。 如果是这样,那么您会知道它发生在上午12点之前。 之后,您可能会回到晚上10点。 如果菜都没有 ,你现在已经缩小的时限从10点至12点-换句话说,你已经晚上10点之前排除了任何时候。 您将继续此过程,直到找到罪魁祸首。

    What would have taken you up to 24 hours, if you had watched the footage in its entirety, now only takes a few seconds.

    如果您完整地观看了整个视频,那么最多需要24小时才能完成,现在只需几秒钟。

    Whether you knew it or not, the specific process we just went through is a binary search! A binary search is a very specific way of hopping back and forth in the footage.

    无论您是否知道,我们刚刚经历的特定过程都是二进制搜索! 二进制搜索是在素材中来回跳动的非常特定的方式。

    Namely, the footage is split at its midpoint to check for the dishes each time. Notice how the distance to the midpoint gets exponentially smaller with each click.

    即,镜头在其中点被分割以每次检查菜肴。 请注意,每次点击到中点的距离如何呈指数减小。

    Binary searches are used to find elements quickly and efficiently. The catch, though, is that binary searches only work when the structure you’re looking through is sorted.

    二进制搜索用于快速有效地查找元素。 不过,要注意的是, 二进制搜索仅在您浏览的结构被排序时才起作用

    In the Nest Cam example, what is the footage sorted by? What are we looking for within that sorted arrangement?

    在Nest Cam示例中,素材按什么排序? 我们在这种排序安排中寻找什么?

    In this case, the data we are searching is sorted by time. Time allows for a linear measurement. Therefore, it allows us to perform a binary search to find someone who doesn’t wash their dishes within a matter of seconds.

    在这种情况下,我们正在搜索的数据将按时间排序。 时间允许进行线性测量。 因此,它使我们可以执行二进制搜索来查找在几秒钟内不洗碗的人。

    We also need something that we’re looking for. In this case, it’s the presence of unwashed dishes in the communal sink.

    我们还需要寻找的东西。 在这种情况下,公共水槽中存在未洗碗。

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

    While programming, a binary search can be used in a multitude of contexts. It’s an extremely quick way to find elements within a sorted structure.

    在编程时,可以在多种环境中使用二进制搜索。 这是在排序的结构中查找元素的非常快速的方法。

    Binary searches can be implemented in an iterative or recursive fashion. An iterative implementation uses a while loop. Meanwhile, a recursive implementation will call itself from within its own body.

    二进制搜索可以迭代或递归的方式实现。 迭代实现使用while循环。 同时,递归实现将在其自身内部进行调用。

    In code, I’ll be performing a binary search on a relatively simple, sorted set of data to highlight the core implementation of a binary search.

    在代码中,我将对相对简单的排序数据集执行二进制搜索,以突出显示二进制搜索的核心实现。

    Given an array of sorted numbers, return True if 53 is an element.

    给定一个有序数字数组,如果53是一个元素,则返回True

    [0, 3, 4, 5, 6, 15, 18, 22, 25, 27, 31, 33, 34, 35, 37, 42, 53, 60]

    迭代式 (Iterative)

    In the iterative approach, a while loop runs until the range of possibilities is zero. This is done by changing the upper and lower bounds of where we are looking and calculating the middle index of that range.

    在迭代方法中,运行while循环直到可能性范围为零。 这是通过更改我们所查看位置的上限和下限并计算该范围的中间索引来完成的。

    The range exists between the lower and upper bounds, inclusive of the bounds themselves.

    范围存在于上下限之间,包括上限本身。

    Before the while loop begins, the lower bound is zero and the upper bound is the length of the array. The upper bound changes if the number we’re looking for is in the first half of the range. The lower bound changes if the number we’re looking for is in the second half of the range.

    while循环开始之前,下限为零,上限为数组的长度。 如果我们要查找的数字在范围的前半部分,则上限会更改。 如果我们要查找的数字在范围的下半部,则下界会改变。

    If the while loop finishes, meaning there is a range of length zero, return False.

    如果while循环结束,这意味着长度范围为零,则返回False

    def binarySearch(array, number):   lowerBound = 0   upperBound = len(array)
    while lowerBound < upperBound:        middleIndex = int(math.floor(lowerBound + (upperBound —    lowerBound) / 2))        if array[middleIndex] == number:             return True        elif array[middleIndex] < number:             lowerBound += 1        elif array[middleIndex] > number:             upperBound = middleIndex   return False

    I’d like to elaborate on this equation:

    我想详细说明这个等式:

    int(math.floor(lowerBound + (upperBound — lowerBound) / 2))

    int(math.floor(lowerBound + (upperBound — lowerBound) / 2))

    The length of the range is calculated by subtracting the lower bound from the upper bound. However, knowing how long the range is isn’t enough.

    长度 范围是通过从上限减去下限来计算的。 但是,仅知道范围多远是不够的。

    At this point, we don’t know which indexes to check in the array. So we are shifting up the array by the lower bound.

    在这一点上,我们不知道要检查数组中的索引。 因此,我们将数组上移下限。

    We then divide that by two, and round down, to get the middle index of the range. math.floor returns a float, so we also have to cast the result to an int.

    然后,我们将其除以2,然后向下舍入以获得该范围的中间索引。 math.floor返回一个float ,因此我们还必须将结果转换为int

    递归的 (Recursive)

    In the recursive approach, the function will call itself from within its body.

    在递归方法中,该函数将在其体内调用自身。

    The upper bound in this function is the length of the array passed in. Again, the upper bound changes if the number we’re looking for is in the first half of the array. The lower bound changes if the number we’re looking for is in the second half of the array.

    此函数的上限是传入的数组的长度。同样,如果我们要查找的数字在数组的前半部分,则上限也会改变。 如果我们要查找的数字在数组的后半部分,则下界会改变。

    def binarySearch(array, number):    middleIndexOfArray = int(math.floor(len(array) / 2))    if middleIndexOfArray == 0:        return False
    if array[middleIndexOfArray] == number:        return True   elif array[middleIndexOfArray] > number:        return binarySearch(array[:middleIndexOfArray], number)   elif array[middleIndexOfArray] < number:        return binarySearch(array[middleIndexOfArray:], number)

    The function then calls itself, passing in an argument of an array half the length of the array that was its argument.

    然后,该函数调用自身,传入一个数组实参,该数组实参的长度是该数组实参的一半。

    If there are zero elements in the array, return False.

    如果数组中的元素为零,则返回False

    The code is available on my Algorithms and Data Structures repo — star it to stay updated!

    该代码在我的算法和数据结构存储库中可用-对其加注星标以保持更新!

    下一步 (Next Steps)

    I wrote my first binary search to implement a stochastic sampling algorithm. It generates a sentence based on the frequency of words in a corpus of text.

    我编写了第一个二进制搜索以实现随机采样算法。 它根据文本语料库中单词的出现频率生成一个句子。

    Feel free to try and build a similar project, which has quite a bit of prep before you can implement the binary search. Or think of your own projects and share them in the comments!

    随意尝试构建一个类似的项目,该项目在实现二进制搜索之前已经做了很多准备。 或考虑自己的项目并在评论中分享!

    This is the second post of my algorithm and data structures series. In each post, I’ll present a problem that can be better solved with an algorithm or data structure to illustrate the algorithm/data structure itself.

    这是我的算法和数据结构系列的第二篇文章。 在每篇文章中,我将介绍一个可以通过算法或数据结构更好地解决的问题,以说明算法/数据结构本身。

    Star my algorithms repo on Github and follow me on Twitter if you’d like to follow along!

    在Github上为我的算法存储库加注星标,如果您想跟随我,在Twitter上关注我!

    翻译自: https://www.freecodecamp.org/news/binary-search-algorithm-7170ae244438/

    二进制搜索算法

    展开全文
  • 二进制搜索算法Binary Search is the most popular Searching Algorithm which is most asked in coding interviews. Its popularity is because of it’s time complexity, where the linear search algorithm ...

    二进制搜索算法

    Binary Search is the most popular Searching Algorithm which is most asked in coding interviews. Its popularity is because of it’s time complexity, where the linear search algorithm takes O(N) time, the Binary Search takes O(log N) time. The only condition in Binary Search is that the array should be sorted.

    二进制搜索是最流行的搜索算法,在编码面试中要求最多。 它的流行是因为它具有时间复杂性,其中线性搜索算法需要O(N)时间,二进制搜索需要O(log N)时间。 Binary Search中的唯一条件是应对数组进行排序。

    In this article, I am going to solve a tricky problem of Binary Search asked in LeetCode called “Find the minimum element in a Rotated and Sorted array” or “Find the Pivot Element in the Rotated and Sorted array”

    在本文中,我将解决一个棘手的问题,即在LeetCode中提出的二进制搜索问题称为“在旋转和排序数组中查找最小元素”在旋转和排序数组中查找枢轴元素”

    This is a tricky problem because it cannot be solved by the standard Binary Search Algorithm since the array is rotated.

    这是一个棘手的问题,因为标准的二进制搜索算法无法解决此问题,因为该数组已旋转。

    问题陈述: (Problem Statement:)

    Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.(i.e.,  [0,1,2,4,5,6,7] might become  [4,5,6,7,0,1,2]).Find the minimum element.Input: [3,4,5,1,2] 
    Output: 1

    问题的方法: (Problem’s Approach:)

    The reason why Binary Search provides O(log N) time complexity is that on each iteration it eliminates half of the array and searches the element in the remaining half.

    二进制搜索提供O(log N)时间复杂度的原因是,每次迭代都会消除数组的一半,并在剩余的一半中搜索元素。

    We need to implement the same approach here and find a way to eliminate half of the array in each iteration.

    我们需要在此处实现相同的方法,并找到一种在每次迭代中消除一半数组的方法。

    问题的解决方案: (Problem’s Solution:)

    Let us look at this rotated array example carefully:

    让我们仔细看一下这个旋转数组的例子:

    Example: [4,5,6,7,0,1,2] // minimum element 0 at index 5

    By observing the array we can conclude two points:

    通过观察数组,我们可以得出两点结论:

    1. The index of the minimum element is the same as the number of rotations of the array

      最小元素的索引与数组的转数相同
    2. The minimum element is smaller than its adjacents

      最小元素小于其相邻元素

    But How do we eliminate one half of the array through Binary Search?

    但是,如何通过二进制搜索消除数组的一半呢?

    The approach is similar to the standard binary search where we find the middle element of the array but the condition changes. Hence by modifying the standard Binary Search Algorithm we get the solution.

    该方法类似于标准二进制搜索,在标准二进制搜索中,我们找到了数组的中间元素,但条件发生了变化。 因此,通过修改标准的二进制搜索算法,我们得到了解决方案。

    When we find the middle element ( in the above example number 7 is the middle element ) we can observe that the array is divided into two halves where one half is sorted and the other half is unsorted. Another interesting observation is that the minimum element is always in the unsorted half.

    当我们找到中间元素(在上面的示例中,数字7是中间元素)时,我们可以观察到数组被分为两半,其中一半被排序而另一半未被排序。 另一个有趣的发现是,最小元素始终位于未排序的一半中。

    Algorithm:

    算法:

    1. Find the middle element of the array.

      找到数组的中间元素。
    2. Check if the middle element is the minimum element

      检查中间元素是否为最小元素
    3. If the middle element does not satisfy the minimum element condition then apply binary search on the unsorted half of the array.

      如果中间元素不满足最小元素条件,则对数组的未排序部分应用二进制搜索。

    Code Implementation in Javascript:

    Java代码实现:

    Step 1: Set left and right values. In this problem, the left value is 0 and the right value is the length of the array.

    步骤1:设定左右数值。 在此问题中,左值为0,右值为数组的长度。

    let left = 0;
    let right = nums.length - 1;

    Step 2: Find the middle element of the array and check for the unsorted half of the array.

    步骤2:找到数组的中间元素,然后检查数组的未排序部分。

    const mid = Math.floor((left + right) / 2);if (arr[mid] > arr[right]) {
    left = mid + 1;
    } else {
    right = mid;
    }

    When the middle value is greater than the rightmost value of the array, it shows that the right half of the array is unsorted, or else the left side is unsorted.

    当中间值大于数组的最右值时,表明数组的右半部分未排序,否则左侧未排序。

    Step 3: Return the answer. The loop breaks when the left is greater than or equal to the right value. This happens when we have found the minimum element in the array as both left and right are equal we return the left index.

    步骤3:返回答案。 当left大于或等于right值时,循环中断。 当我们在数组中找到最小元素时(左和右相等),就会发生这种情况,因为我们返回左索引。

    return arr[left];

    最终解决方案: (Final Solution:)

    var findMinelement = function(arr) {
        let left = 0;
        let right = nums.length - 1;  
        while (left < right) {
            const mid = Math.floor((left + right) / 2);
            if (arr[mid] > arr[right]) {
              left = mid + 1;
            } else {
              right = mid;
            }
        }
    
    
        return arr[left];
    };

    Thank you for reading the article till the end, hope this article will help you in your coding preparations. All the best!!!

    感谢您阅读本文直到最后,希望本文对您的编码准备有所帮助。 祝一切顺利!!!

    翻译自: https://medium.com/nerd-for-tech/modified-binary-search-algorithm-to-solve-tricky-problems-92399b193206

    二进制搜索算法

    展开全文
  • 二进制树型搜索算法 二进制搜索算法 (Binary Search Algorithm) 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 ...

    二进制树型搜索算法

    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 of middle elements
        int step = 0;  // to find out in how many steps we completed the search
        
        while(max >= min)
        {
            guess = (max + min) / 2;
            // we made the first guess, incrementing step by 1
            step++;
            
            if(values[guess] ==  target)
            {
                printf("Number of steps required for search: %d \n", step);
                return guess;
            }
            else if(values[guess] >  target) 
            {
                // target would be in the left half
                max = (guess - 1);
            }
            else
            {
                // target would be in the right half
                min = (guess + 1);
            }
        }
     
        // We reach here when element is not 
        // present in array
        return -1;
    }
     
    int main(void)
    {
        int values[] = {13, 21, 54, 81, 90};
        int n = sizeof(values) / sizeof(values[0]);
        int target = 81;
        int result = binarySearch(values, n, target);
        if(result == -1)
        {  
            printf("Element is not present in the given array.");
        }
        else
        {
            printf("Element is present at index: %d", result);
        }
        return 0;
    }

    We hope the above code is clear, if you have any confusion, post your question in our Q & A Forum.

    我们希望上面的代码清晰明了,如果您有任何疑问,请在我们的“ 问答论坛”中发布您的问题。

    Now let's try to understand, why is the time complexity of binary search O(log n) and how can we calculate the number of steps required to search an element from a given array using binary search without doing any calculations. It's super easy! Are you ready?

    现在让我们尝试理解,为什么二分查找的时间复杂度为O(log n),以及如何在不进行任何计算的情况下使用二分查找来计算从给定数组中搜索元素所需的步数。 超级容易! 你准备好了吗?

    二元搜索的时间复杂度O(log n) (Time Complexity of Binary Search O(log n))

    When we say the time complexity is log n, we actually mean log2 n, although the base of the log doesn't matter in asymptotic notations, but still to understand this better, we generally consider a base of 2.

    当我们说时间复杂度是log n ,我们实际上是指log 2 n ,尽管对数的底数在渐进表示法中并不重要,但是为了更好地理解这一点,我们通常考虑2的底数。

    Let's first understand what log2(n) means.

    首先让我们了解log 2 (n)含义。

    Expression: log2(n) - - - - - - - - - - - - - - - For n = 2: log2(21) = 1 Output = 1 - - - - - - - - - - - - - - - For n = 4 log2(22) = 2 Output = 2 - - - - - - - - - - - - - - - For n = 8 log2(23) = 3 Output = 3 - - - - - - - - - - - - - - - For n = 256 log2(28) = 8 Output = 8 - - - - - - - - - - - - - - - For n = 2048 log2(211) = 11 Output = 11

    表达式:log 2 (n)---------------对于n = 2:log 2 (2 1 )= 1输出= 1------------ ---对于n = 4 log 2 (2 2 )= 2输出= 2----------------对于n = 8 log 2 (2 3 )= 3输出= 3-- --------------对于n = 2048 log 2 (n = 256 log 2 (2 8 )= 8输出= 8---------------- 2 11 )= 11输出= 11

    Now that we know how log2(n) works with different values of n, it will be easier for us to relate it with the time complexity of the binary search algorithm and also to understand how we can find out the number of steps required to search any number using binary search for any value of n.

    现在我们知道如何log 2 (n)与不同价值观的作品n ,这将是我们更容易与二进制搜索算法的时间复杂度有关,同时还应了解我们如何能够找出需要的步数使用二进制搜索n任何值来搜索任何数字。

    计算步数 (Counting the Number of Steps)

    As we have already seen, that with every incorrect guess, binary search cuts down the list of elements into half. So if we start with 32 elements, after first unsuccessful guess, we will be left with 16 elements.

    正如我们已经看到的,每进行一次错误的guess ,二进制搜索就会将元素列表缩减为一半。 因此,如果我们从32个元素开始,则在第一次失败的猜测之后,我们将剩下16个元素。

    So consider an array with 8 elements, after the first unsuccessful, binary sort will cut down the list to half, leaving behind 4 elements, then 2 elements after the second unsuccessful guess, and finally only 1 element will be left, which will either be the target or not, checking that will involve one more step. So all in all binary search needed at most 4 guesses to search the target in an array with 8 elements.

    因此,考虑一个包含8个元素的数组,在第一个不成功的二进制排序之后,将列表减半,剩下4个元素,然后在第二个不成功的猜测之后保留2个元素,最后只剩下1个元素,或者是否达到target ,检查将涉及更多步骤。 因此,所有二进制搜索最多需要4个猜测才能在具有8个元素的数组中搜索target

    If the size of the list would have been 16, then after the first unsuccessful guess, we would have been left with 8 elements. And after that, as we know, we need atmost 4 guesses, add 1 guess to cut down the list from 16 to 8, that brings us to 5 guesses.

    如果列表的大小为16,则在第一次不成功的猜测之后,我们将剩下8个元素。 然后,据我们所知,我们最多需要4个猜测,再加上1个猜测就可以将列表从16个减少到8个,这使我们得到5个猜测。

    So we can say, as the number of elements are getting doubled, the number of guesses required to find the target increments by 1.

    因此,可以说,随着元素数量增加一倍,找到target所需的猜测数量将增加1

    Seeing the pattern, right?

    看到图案了吧?

    Generalizing this, we can say, for an array with n elements,

    概括地说,对于具有n元素的数组,

    n, until we get the value 1, plus one.n开始可以重复减半的次数,直到获得值1加1。

    And guess what, in mathematics, the function log2 n means exactly same. We have already seen how the log function works above, did you notice something there?

    并猜想在数学上,函数log 2 n含义是完全相同的。 我们已经在上面看到了log函数的工作方式,您在那儿注意到了吗?

    For n = 8, the output of log2 n comes out to be 3, which means the array can be halved 3 times maximum, hence the number of steps(at most) to find the target value will be (3 + 1) = 4.

    对于n = 8 ,对log 2 n的输出为3 ,这意味着该数组可以减半为最大3倍,因此(最多)查找目标值的步骤数将为(3 +1)= 4。

    Question for you: What will be the maximum number of guesses required by Binary Search, to search a number in a list of 2,097,152 elements?

    您的问题:二进制搜索要搜索2097152个元素列表中的数字,最大猜想数是多少?

    翻译自: https://www.studytonight.com/data-structures/binary-search-algorithm

    二进制树型搜索算法

    展开全文
  • 二进制搜索算法结构模型对象二进制编组
  • 二进制搜索算法

    千次阅读 2020-05-19 23:20:52
    : 一种常用的算法二进制搜索。 如果您还不知道,请继续阅读。 非常有帮助。 节省大量CPU。 以指数方式减少计算。 当搜索大量信息以查找匹配项时,想到的第一个想法是线性搜索。 遍历所有值以查找匹配项。 如果...

    为什么?:

    一种常用的算法是二进制搜索。

    如果您还不知道,请继续阅读。

    非常有帮助。 节省大量CPU。 以指数方式减少计算。

    当搜索大量信息以查找匹配项时,想到的第一个想法是线性搜索。 遍历所有值以查找匹配项。 如果找到它,请返回位置或值,然后结束搜索。

    然而,当要搜索的值变得非常大时,这变得非常低效。 这是O(N)算法。 在更坏的情况下,您可能必须搜索所有值以找到匹配项,甚至更糟的是找到不存在的匹配项!

    怎么样?:

    项目列表是否可以数字或ASCII排序。 使用二进制搜索!

    首先,对列表进行排序,然后将最中间的值(如果列表元素不均匀,则向上或向下)与搜索词进行比较。 如果它是“少于”您的用语,则说明它一定是

    低于那个点。 这样就可以消除上限。 如果该术语的值大于中心点的值,请消除该较低的范围。

    因此将要搜索的项目数量减少了一半。

    将此技术连续应用于其余项目,并将每次迭代的搜索量减少一半。

    因此以更快的O(log N)算法运行。

    示例: 警告 :使用“递归”,切记要考虑CPU上的函数调用负载。 在某些语言中,这实际上可能比线性慢。 请参阅下面的非递归。

    (摘自

    维基百科
    
    BinarySearch(A[0..N-1], value, low, high) {
           if (high < low)
               return -1 // not found
           mid = low + ((high - low) / 2)  // Note: not (low + high) / 2 !!
           if (A[mid] > value)
               return BinarySearch(A, value, low, mid-1)
           else if (A[mid] < value)
               return BinarySearch(A, value, mid+1, high)
           else
               return mid // found
       } 
    这里有一个优化。

    有时在处理大量数字或浮点数时精度很高。

    中=(低+高)/ 2

    可能会溢出并占用内存,从而导致结果不可靠。

    中=低+((高-低)/ 2)

    解决它。 :)

    看到这里... 非递归:
    
    low = 0
           high = N
           while (low < high) {
               mid = low + ((high - low) / 2)  // Note: not (low + high) / 2 !!
               if (A[mid] < value)
                   low = mid + 1; 
               else
                    //can't be high = mid-1: here A[mid] >= value,
                    //so high can't be < mid if A[mid] == value
                    high = mid; 
           }
           // high == low, using high or low depends on taste 
           if ((low < N) && (A[low] == value))
               return low // found
           else
               return -1 // not found       

    这个最基本的算法有很多资源。 只需在Google中输入“二进制搜索”即可。

    祝您编程愉快。

    From: https://bytes.com/topic/algorithms/insights/867454-binary-search-algorithm

    展开全文
  • c语言 二进制压缩算法by Pablo E.... 使用C ++解释的二进制搜索算法 (Binary Search Algorithms Explained using C++) Binary search is one of those algorithms that you’ll come across on every (good) introdu...
  • 求一个二进制搜索算法 Linear search (searching each index in an array one by one) works almost everywhere but it is not optimal in many cases. Let's assume, we have a book which has429496729...
  • 二进制搜索算法by Divya Godayal 通过Divya Godayal 二进制搜索的一个扭曲故事 (A twisted tale of Binary Search) Awesome. That’s how I feel right now. Writing my first solo tech article. 太棒了 那就是我...
  • 在本文中,我将比较线性搜索和二进制搜索算法。 您将看到每种算法的伪代码,以及示例和实现每种方法的逐步指南。 介绍 作为程序员,您想找到问题的最佳解决方案,以使您的代码不仅正确而且高效。 选择次优算法可能...
  • 基于标签分组的RFID系统改进二进制搜索算法,田广东,周全,目前,无线射频识别(RFID)在仓库、供应链管理、零售、追踪和医疗保健等许多领域得到广泛应用。 然而,RFID技术中的碰撞问题严重影
  • 动态二进制搜索算法是在传统二进制算法的基础上进行改进的。 传统二进制算法,每次传输的数据是全部长度的序列号,造成了识读时间段浪费;因此动态的二进制搜索算法在每次传输中,阅读器传输一部分,标签传输一部分...
  • 流行的二进制搜索算法的迭代实现,用于在排序数组中查找元素。 (An Iterative implementation of the popular binary search algorithm to find an element in a sorted array.) Hello everyone! I have publ...
  • Binary search also known as half-interval search, logarithmic search is an algorithm used in computers to find ... 二进制搜索也称为半间隔搜索 , 对数搜索是计算机中用于查找排序数组中值位置的算法。 Bub...
  • 算法考虑当随机索引i处的元素等于搜索值时的情况,在这种情况下它返回true,而第种情况是当索引i处的元素大于搜索值时,在这种情况下我们递归地调用搜索在i – 1的输入n上.如果元素总是大于或等于搜索值,那么算法工作...
  • Binary Search is a simple algorithm to find an item in an sorted array, and it’s usually referenced as a code sample to study when learning a new ... Binary Search是一种简单的算法,可以在排序后的数...
  • 比如 在一段BYTe数组中 {0x11,0x22,0x33,0x44,0x55,0x66,0x77} ...搜索0x22 ?? 0x44 能返回0x22的索引 搜索 0x33 ?? ?? 0x66 能返回0x33的索引 总之就是可以匹配问号搜索即可 谢谢了
  • <p>In <code>Binary Search Algorithm, <p>in general <pre><code>if mid_value > search_element we set high = mid_pos-1 ;...else mid_value < search_element we set low = mid_pos+1 ;...
  • 实现此PPT上的内容,算法要从PPT上提取; 代码// author:seen // thinks : instruction on string #include #include using namespace std; struct str{ string s; }S[10]; bool trek[4]; void main() {
  • 在RFID系统中,为解决碰撞问题,必须采用一定的防碰撞算法,时分多址算法中的二进制搜索算法识别率较高,是RFID系统中最常用的防碰撞算法。介绍了常用防碰撞算法的原理,并详细分析了二进制搜索算法的原理和实现过程,最后...
  • 动态二进制树搜索算法 二进制搜索树 (Binary Search Tree) A binary search tree is a useful data structure for fast addition and removal of data. 二进制搜索树是用于快速添加和删除数据的有用数据结构。 It...
  • 二进制树形搜索算法 二进制搜索用于在 值的排序列表 。 它选择排序值数组中的中间元素,并将其与目标值进行比较; 这就是我们在数组中寻找的关键。 如果它小于目标值,则在中间元素之后搜索,直到数组末尾。 如果...
  • 基于机器学习的RFID二进制碰撞算法优化,张科,宋峥,本文在保证二进制搜索算法高准确度的基础上,以尽量缩短RFID识别时间为最终目的。通过对一个具体环境的分析,利用机器学习的方法��
  • 二进制搜索法 java 介绍 (Introduction) In this tutorial, we are going to learn about the Binary Search... 在本教程中,我们将学习二进制搜索算法并在Java中实现它。 Normal Linear or sequential search algo...
  • 物联12:二进制树型搜索算法

    万次阅读 2015-04-15 10:43:49
     纯ALOHA算法和时隙ALOHA算法的信道最佳利用率为18.4%和36.8%,随着标签数量的增加,其性能急剧恶化,因此人们提出了二进制搜索算法。二进制防碰撞算法基于轮询的办法,按照二进制树模型和一定的顺序对所有的可能...
  • 这周的任务是用Java实现二进制搜索 ,您需要编写迭代和递归二进制搜索算法 。 在计算机科学中,二进制搜索或半间隔搜索是一种分而治之的算法,用于在排序数组中定位项目的位置。 二进制搜索通过将输入值与数组的...
  • 本周的任务是用Java实现二进制搜索 ,您需要编写迭代和递归二进制搜索算法 。 在计算机科学中,二进制搜索或半间隔搜索是一种分而治之的算法,用于定位项目在排序数组中的位置。 二进制搜索通过将输入值与数组的中间...
  • 合并排序和二进制搜索 创建该程序的目的是演示和实践我对递归编程,合并排序算法和二进制搜索算法的了解。

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 786
精华内容 314
关键字:

二进制搜索算法