精华内容
下载资源
问答
  • 二进制搜索算法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

    二进制树型搜索算法

    展开全文
  • 二进制搜索算法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. 太棒了 那就是我...

    二进制搜索算法

    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.

    太棒了 那就是我现在的感觉。 写我的第一篇个人技术文章。

    I must say I have a lot to share with you guys, and have a lot more to learn as well. So without any further ado, lets get to it. And yes, hold on tight — ‘cause there is a twist in the tale. ?

    我必须说,我有很多可以与你们分享的东西,并且还有很多东西要学习。 因此,事不宜迟,让我们开始吧。 是的,请紧紧握住-因为故事有个转折。 ?

    All of us have heard of the classic 2 Eggs and 100 Stories problem. I have something similar for you.

    我们所有人都听说过经典的2个鸡蛋和100个故事问题。 我有类似的东西给你。

    You have a 100 story building with a rule:

    您有一个具有规则的100层建筑:

    People with pets can only occupy top floors

    People with pets can only occupy top floors

    Your friend wishes to buy an apartment in this building. She is too scared of pets to live near them, but you love them. She asked if you can help her find out where exactly the pet friendly floors start. She wants to explore all of the different options available, and so you need to find out which floors starting from the ground up are the ones that don’t allow pets.

    您的朋友希望在此建筑物中购买公寓。 她太怕宠物了,不能住在附近,但你爱它们。 她问您是否可以帮助她找出宠物友好地板的确切位置。 她想探索所有可用的不同选项,因此您需要找出从头开始的哪些楼层不允许宠物入内。

    The building management folks are on a holiday. On every floor, there is a sign board next to the elevator telling you if the floor is pet friendly or not. But you are too lazy to stop at every floor to check the pet sign board since the lift is so slow.

    建筑管理人员正在度假。 在每层楼上,电梯旁边都有一个告示牌,告诉您该楼层是否可养宠物。 但是,由于电梯太慢,您懒得在每个楼层停下来检查宠物指示牌。

    What do you do?

    你是做什么?

    The lift takes almost a minute at every floor to stop and then start again. Yes that’s how bad it is. But between the floors, navigation is pretty smooth. You have to get this done quickly.

    电梯在每层都需要花费近一分钟的时间才能停止,然后重新开始。 是的,那真是太糟糕了。 但是在楼层之间,导航非常流畅。 您必须快速完成此任务。

    How do you go about it ?

    你如何去做?

    迭代法 (Iterative approach)

    One naïve approach to this would be to start at the very bottom of the building (the ground floor) and keep stopping the lift at every single floor to check the sign that floor has posted. You stop when you find the pet friendly sign.

    一种简单的方法是从建筑物的最底端(底层)开始,并在每一层都停下电梯,以检查该层已张贴的迹象。 找到宠物友好标志时,您将停下来。

    Best case is that the ground floor has the pet sign. Meaning the entire building has pets. No way your friend would buy an apartment here.

    最好的情况是一楼有宠物标志。 意思是整个建筑都养宠物。 您的朋友绝对不会在这里购买公寓。

    Average case is that you go to the 50th floor, stopping at every floor in between, and finally find a pet sign board. So your friend can buy one from 1–49.

    一般情况是,您去了50楼,停在中间的每一层,最后找到一个宠物告示板。 这样您的朋友可以从1到49购买一个。

    Worst case scenario would be you reaching the 100th floor, stopping at every floor on the way up, only to find out that there are no pet sign boards in the entire building. So your friend can buy any apartment from 1–100, but who cares, it took you almost two hours to find that out. ? ?.

    最糟糕的情况是,您到达100楼,在上升的每一层都停下来,却发现整个建筑物中没有宠物告示板。 因此,您的朋友可以购买1100至100欧元之间的任何公寓,但谁在乎,您花了将近两个小时才找到答案。 ? ?

    Algorithmically, given an array of 100 boolean values, the index of the array represents building floors and a 0 represents a floor where no pets are allowed while a 1 represents a floor where pets would be allowed. From the rule of the building, the array would be of the form

    从算法上讲,给定一个包含100个布尔值的数组,该数组的索引表示建筑物楼层,0表示不允许宠物进入的楼层,而1表示允许宠物进入的楼层。 根据建筑物的规则,数组的形式为

    000... 1111...

    that is, all 0s followed by all 1s, because only the top floors can be the ones where pets are allowed.

    也就是说,全0后面全为1,因为只有顶层可以带宠物。

    Given this array, we need to find the first index where there is a 1 . A linear search algorithm for this problem would be as simple as iterating over the array and looking for a 1 and returning when we find one.

    给定此数组,我们需要找到第一个索引为1 。 解决这个问题的线性搜索算法就像在数组上迭代并寻找1并在找到一个返回时一样简单。

    As expected, the complexity of this algorithm would be O(n) where n = 100 for our specific building example. You need to come up with something faster than this. Stopping at every floor is not feasible, as it would take you a lot of time to cover the entire building in the worst case.

    不出所料,此算法的复杂度为O(n) ,其中对于我们的特定建筑示例,n = 100。 您需要提出比这更快的方法。 在每一层都停下来是不可行的,因为在最坏的情况下,要花费很多时间才能覆盖整个建筑物。

    二进制搜索法 (Binary Search Approach)

    Let’s say you start from ground floor and got to the 50th floor with no stops. At the 50th floor, you stopped and got out of the lift and checked for the sign. The board sign said “No Pets”. This would mean that, until the 50th floor, there are definitely no pets.

    假设您是从一楼开始,一直到50楼而已。 在50楼,您停下来,走出电梯,检查招牌。 板子上写着“No Pets” 。 这意味着直到50楼,绝对没有宠物。

    So now knowing that you reduce your search space to the other half, which is floors 51–100. This means that with a single stop, you were able to cover half of the building knowing for sure that the first half doesn’t have any pets. That’s amazing!

    因此,现在您知道将搜索空间减小到另一半,即第51-100层。 这意味着您只需停下来,就可以覆盖整个建筑物的一半,同时要确保前半部分没有宠物。 棒极了!

    Moving on, you again divide your remaining set of floors into half and take the lift and go directly to the 75th floor. And you see a “Pets” sign board there. This means the floor where it started showing up must be between 50–75. You can keep following a similar approach of diving the remaining floors into half and checking until you find the first floor with the “Pets” sign board.

    继续前进,您再次将剩余的楼层分成两半,乘坐电梯,直接进入第75层。 然后您会看到一个“Pets”标志牌。 这意味着开始显示的地板必须在50-75之间。 您可以继续采用类似的方法,将剩余的楼层分成两半,然后进行检查,直到找到带有“Pets”标志牌的第一层为止。

    You see, every time you make a decision, you divide your search space into two halves and go ahead with one half of the search space. That’s how we narrow down our search. Since we always divide the search space in two and choose one over the other, that is why this type of search strategy is called a Binary search strategy.

    您会看到,每次做出决定时,您都会将搜索空间分为两半,然后继续进行一半的搜索空间。 这就是我们缩小搜索范围的方式。 由于我们总是将搜索空间一分为二,然后选择一个,因此这就是为什么这种搜索策略称为Binary搜索策略。

    Isn’t that way faster?

    这样不是更快吗?

    Let’s look into the algorithm for this.

    让我们研究一下算法。

    If you’ve been following along closely and have a grasp of the algorithm, you would have realized a hard and fast condition for the binary search algorithm to work. The condition is that the array needs to be sorted beforehand. In our example, the building floors were sorted from 1–100 and we could easily divide the search space in two.

    如果您一直密切关注并掌握了该算法,那么您将认识到二进制搜索算法工作的艰巨条件。 条件是该数组需要事先排序。 在我们的示例中,建筑物楼层的分类范围为1–100,我们可以轻松地将搜索空间分为两部分。

    Let’s look at an example array which is sorted and try and search for an element in it.

    让我们看一个示例数组,该数组已排序并尝试在其中搜索元素。

    In the above example, the element to be searched is 8. The given array is a sorted array in increasing order. Once we find the middle element (which is 5), we see that the element to be searched is greater than the current index element. Since the array is sorted in increasing order, 8 would lie on the right of the array and can never be on the left side.

    在上面的示例中,要搜索的元素为8。给定数组是按升序排序的数组。 找到中间元素(为5)后,我们看到要搜索的元素大于当前索引元素。 由于数组是按升序排序的,因此8将位于数组的右侧,并且永远不能位于左侧。

    So we ignore the elements to the left of 5 and continue our search with the remaining elements, eventually finding out 8.

    因此,我们忽略5左边的元素,并继续搜索其余元素,最终找到8。

    On the other hand, what if the array is not sorted? Even though we know the current element is 5 and we know we need to search for 8, we are not sure which direction is the right way to go. If we end up thinking the array is sorted and apply binary search and go to the right part, we will never find 8.

    另一方面,如果数组未排序怎么办? 即使我们知道当前元素是5并且知道需要搜索8,我们也不确定哪个方向是正确的方向。 如果我们最终认为数组已排序并应用二进制搜索然后转到正确的部分,我们将永远找不到8。

    So binary search essentially wants your array to be sorted.

    因此,二进制搜索本质上是希望对数组进行排序。

    That was the standard binary search algorithm that we just looked at. But, as the title of the article suggests, there is a twist in the tale!

    那就是我们刚刚研究过的标准二进制搜索算法。 但是,正如文章标题所暗示的,这个故事有一个转折!

    I am an avid competitive programmer, and there was an interesting variant of the binary search algorithm in the CodeChef May Long Challenge.

    我是一个狂热的竞争程序员,在CodeChef May Long Challenge中有一个有趣的二进制搜索算法变体。

    Essentially, the Chef wrote the classic binary search, assuming the input array would be sorted. All the other children in the class copied the code from him, as Chef is the best programmer in the class. His assumption could’ve cost the entire class their assignment marks, as the input array was not sorted beforehand.

    本质上,Chef编写了经典的二进制搜索,并假设输入数组将被排序。 班上所有其他孩子都从他那里复制了代码,因为Chef是班上最好的程序员。 他的假设可能使整个类失去了分配标记,因为输入数组未事先排序。

    The only thing the Chef can do is to preprocess the array by swapping some pair of numbers here and there so that the binary search procedure still returns the right index.

    Chef唯一能做的就是通过在这里和那里交换一些数字对预处理数组,以便二进制搜索过程仍然返回正确的索引。

    Note: The preprocessor above should ideally return the modified array for the binary search to work correctly. However, as the problem statement asks, we are just trying to determine the number of swaps needed for binary search to work correctly on the unsorted array given an input. The algorithm would also return a -1 if such a modification is not possible for the given array and element.

    注意:理想情况下,上述预处理器应返回修改后的数组,以使二进制搜索正常工作。 但是,正如问题陈述所要求的,我们只是试图确定在给定输入的情况下,二进制搜索在未排序数组上正确运行所需的交换次数。 如果对于给定的数组和元素不可能进行这种修改,则该算法还将返回-1。

    The idea here is very simple.

    这里的想法很简单。

    We need to understand two basic steps. I call them the TI-ME steps. Perhaps that’ll help you remember what we are doing here.

    我们需要了解两个基本步骤。 我称它们为TI-ME步骤。 也许这可以帮助您记住我们在这里所做的事情。

    a. Target Index: The index of the element to be searched for. We need to know this, since this index would help us drive the modifications. Because every time we modify any element, we need to sail towards this index and not away from it.

    一个。 牛逼 ARGET ndex:要搜索的元素的索引。 我们需要知道这一点,因为该索引将帮助我们推动修改。 因为每次修改任何元素时,我们都需要朝着该索引航行而不是远离它。

    b. Middle Element: If you look clearly in a binary search, it’s the middle element of the current search space which drives the next move. If this middle element takes us in the wrong direction, we need to replace with the appropriate element.

    b。 中号 iddleè字元素:如果您在二进制搜索看清楚,它的驱动下移动当前的搜索空间的中间元素。 如果这个中间元素将我们引向错误的方向,则需要替换为适当的元素。

    So, the whole idea here is that we swap all the middle elements which are wrongly placed.

    因此,这里的整体思想是我们交换所有错误放置的中间元素。

    The binary search algorithm (the value of the middle element with respect to the element to be searched, that is, X) can either take us towards the left half of the array or the right half. So, there are two possibilities for a wrongly placed middle element:

    二进制搜索算法(相对于要搜索的元素而言,中间元素的值,即X)可以将我们带到数组的左半部分或右半部分。 因此,错误放置中间元素有两种可能性:

    1. The element to be searched was on the right of the middle element, but since Element[Mid] > Element[Target Index] , the binary search would have had to ignore the right half and move towards the left half. OR

      要搜索的元素在中间元素的右侧,但是由于Element[Mid] > Element[Target Ind ex],因此二进制搜索将不得不忽略右半部分而向左半部分移动。 要么

    2. The element to be searched was on the left of the middle element, but since Element[Mid] < Element[Target Index] , the binary search would have had to ignore the left half and move towards the right half.

      要搜索的元素在中间元素的左侧,但是由于Element[Mid] < Element[Target Ind ex],因此二进制搜索将不得不忽略左半部分而向右半部分移动。

    Therefore, if a middle element is wrongly placed such that a number X was needed in its place where X < Element[Target Index] , then we maintain a counter for that and call it count_low_needed .

    因此,如果错误地放置了一个中间元素,使得在X < Element[Target Ind ex]的位置需要数字X ,则我们为此维护一个计数器并将it count_low_nee ded。

    Similarly, if a middle element is wrongly placed such that a number X was needed in its place where X > Element[Target Index] , then we maintain a counter for that and call it count_high_needed .

    同样,如果错误地放置了一个中间元素,使得在X > Element[Target Ind ex]的位置需要数字X ,则我们为此维护一个计数器,并将it count_high_nee ded。

    Also, if we simply run the binary search algorithm over the given array while searching for numbers, there would be some numbers that would be correctly placed. These would be the middle elements that drove the binary search in correct directions corresponding to the given element X (the element to be searched). These numbers cannot be a part of the swapping, because they are rightly positioned with respect to X .

    另外,如果我们在搜索数字时仅在给定的数组上运行二进制搜索算法,那么将会正确放置一些数字。 这些将是在与给定元素X (要搜索的元素)相对应的正确方向上推动二进制搜索的中间元素。 这些数字不能作为交换的一部分,因为它们相对于X位置正确。

    Let’s look at the pseudo code for this algorithm first and then go through an example.

    让我们先看一下该算法的伪代码,然后再看一个例子。

    function can_preprocess(arr, X){     low = 0     high= 0
    while X is not found {          mid = (low + high) / 2          if arr[mid] == X {             break                     }
    correctly_placed_low = 0          correctly_placed_high = 0          count_low_needed = 0          count_high_needed = 0
    if `mid` suggests we should go right for X {               if X is actually on the right {                   correctly_placed_low ++               }               else {                   count_low_needed ++               }          } else {               if X is actually on the left {                  correctly_placed_high ++               }                else {                  count_high_needed ++               }          }
    modify low and high according to           where `X` actually is with respect to `mid`
    }
    // Total smaller numbers available for swapping     TSM = sorted_index[X] - correctly_placed_low
    // Total Larger numbers available for swapping     TLM = (N - sorted_index[X]) - correctly_placed_high
    if count_low_needed > TSM or count_high_needed > TLM {          return -1     }
    return max(count_low_needed, count_high_needed)

    NOTE: The problem statement fixes the input array for us and repeatedly passes values to be searched in the input array. So, we can iterate once over the original array to know the actual location of the element to be searched (create a dictionary, essentially).

    注意:问题声明为我们修复了输入数组,并反复传递要在输入数组中搜索的值。 因此,我们可以遍历原始数组一次,以了解要搜索的元素的实际位置(本质上是创建字典)。

    Also, we need sorted_index[X] to tell us how many values are lesser than or greater than the element X in our array. We can sort the array and create another dictionary storing location of each element in the sorted array.

    另外,我们需要sorted_index[X]告诉我们有多少个值小于或大于数组中的元素X 我们可以对数组进行排序,并创建另一个字典来存储排序后的数组中每个元素的位置。

    Let’s go through the steps of the proposed algorithm while dry running an example.

    让我们在尝试运行示例的同时浏览所提出算法的步骤。

    1. Given an unsorted array, you need to search for X = 4 .

      给定一个未排序的数组,您需要搜索X = 4

      Hence our target index is 7.

      因此,我们的目标指数是7。

    2. Mid element index < Target Index, so we need to maneuver our search to the right half. But Element[Mid] > Element[Target Index], hence count_low_needed = 1

    2.中元素索引<目标索引,因此我们需要将搜索调整到右半部分。 但是ut Element[Mid] > Element[Target索引], hence count_low_need ed = 1

    3. Mid element index < Target Index, so we still need to maneuver our search to the right half. Once again, Element[Mid] > Element[Target Index], hence count_low_needed = 2

    3.中元素索引<目标索引,因此我们仍然需要将搜索调整到右半部分。 再次n, Element[Mid] > Element[Target索引], hence count_low_need ed = 2

    4. The total number of swaps needed for binary search to return the correct index here would be two swaps with elements lower than 4. We have smaller numbers 1, 3 or 2 for swapping available, so we can successfully do the swapping for this array so that binary search correctly finds out 4 .

    4.返回此处正确索引的二进制搜索所需的交换总数将是元素小于4的两次交换。我们可以使用较小的数字1, 3 or 2进行交换,因此我们可以成功地对该数组进行交换这样二进制搜索就可以正确找出4

    Below is the Python code for the given problem. Every step is explained in the comments.

    以下是给定问题的Python代码。 注释中说明了每个步骤。

    The time complexity of this Twisted Binary Search algorithm is still O(nlogn) .

    这种扭曲二进制搜索算法的时间复杂度仍为O(nlogn)

    I hope you were able to grasp the inner workings of the binary search algorithm and had fun while going through this interesting problem as well. If you found this post useful, spread the love and share as much as possible. ?

    我希望您能够掌握二进制搜索算法的内部工作原理,并且在经历这个有趣的问题时也很开心。 如果您发现此帖子有用,请传播爱心并尽可能多地分享。 ?

    翻译自: https://www.freecodecamp.org/news/a-twisted-tale-of-binary-search-49f5ac01e83d/

    二进制搜索算法

    展开全文
  • 射频识别技术(RFID)是从20世纪80年代走向成熟的一项自动识别技术[1]。...介绍了常用防碰撞算法原理,并详细分析了二进制搜索算法原理和实现过程,最后对算法的效率进行了研究和比较,得出了改进的建议。
  • 在本文中,我将比较线性搜索和二进制搜索算法。 您将看到每种算法的伪代码,以及示例和实现每种方法的逐步指南。 介绍 作为程序员,您想找到问题的最佳解决方案,以使您的代码不仅正确而且高效。 选择次优算法可能...
    JavaScript

    在本文中,我将比较线性搜索和二进制搜索算法。 您将看到每种算法的伪代码,以及示例和实现每种方法的逐步指南。

    介绍

    作为程序员,您想找到问题的最佳解决方案,以使您的代码不仅正确而且高效。 选择次优算法可能意味着更长的完成时间,增加的代码复杂度或使崩溃的程序更糟。

    您可能已经使用搜索算法来查找数据集合中的项目。 JavaScript语言有多种方法,例如find ,可以在数组中定位项目。 但是,这些方法使用线性搜索。 线性搜索算法从列表的开头开始,并将每个元素与搜索值进行比较,直到找到它为止。

    当元素较少时,这很好。 但是,当您搜索包含数千或数百万个元素的大型列表时,您需要一种更好的方式来查找项目。 这是您将使用二进制搜索的时间。

    在本教程中,我将解释二进制搜索的工作原理以及如何在JavaScript中实现该算法。 首先,我们将回顾线性搜索算法。

    线性搜寻

    我们将首先说明如何在JavaScript中实现线性搜索。 我们将创建一个名为linearSearch的函数,该函数接受一个整数或字符串值以及一个数组作为参数。 该函数将在数组中的每个元素中搜索该值,如果找到该值,则返回该值在数组中的位置。 如果该值不在数组中,则它将返回-1。 例如,调用linearSearch(1, [3, 4, 2, 1, 5])将返回3,而调用linearSearch(0, [3, 4, 2, 1, 5])将返回-1。

    这是我们函数的一些伪代码:

    Set found to false
    Set position to −1
    Set index to 0
    while found is false and index < number of elements
        if list[index] is equal to search value
            Set found to true
            Set position to index
        else Add 1 to index
    return position

    线性搜索JavaScript实现

    这是线性搜索算法JavaScript实现:

    function linearSearch(value, list) {
        let found = false;
        let position = -1;
        let index = 0;
    
        while(!found && index < list.length) {
            if(list[index] == value) {
                found = true;
                position = index;
            } else {
                index += 1;
            }
        }
        return position;
    }

    重要的是要注意,线性搜索算法不需要使用排序列表。 而且,可以自定义算法以用于不同的场景,例如通过键搜索对象数组。 如果您的客户数据数组包含名字和姓氏的键,则可以测试该数组是否有一个具有指定名字的客户。 在这种情况下,您可以检查list[index].first ,而不是检查list[index]是否等于我们的搜索值。

    在上面的示例中,我在具有五个元素的数组上使用了linearSearch函数。 在最坏的情况下,当搜索值不在列表中或不在列表末尾时,该函数将必须进行五次比较。 由于我们的数组很小,因此无需使用其他算法进行优化。 但是,超出某个点,使用线性搜索算法不再有效,也就是说,使用二进制搜索算法会更好。

    二元搜寻

    假设您正在玩数字猜谜游戏。 要求您猜测一个介于1到100之间的数字。如果您的数字太大或太小,都会得到提示。

    您的策略是什么? 您会随机选择数字吗? 您会从1开始,然后从2开始,依此类推,直到猜对为止? 即使您有无限的猜测,您也想通过尽可能少的尝试做出正确的猜测。 因此,您可以从猜测50开​​始。如果数字较高,则可以猜测75。如果数字较低,则表示数字在50到75之间,您可以选择一个中间的数字。 您将继续这样直到到达正确的数字。 这类似于二进制搜索的工作方式。

    与线性搜索不同,二进制搜索使用排序列表。 要搜索值,首先将值与列表的中间元素进行比较。 如果它们相等,则找到搜索值。 如果搜索值大于中间元素,则搜索数据的上半部分。 然后,将本节的中间元素与搜索值进行比较。 或者,如果该项小于中间元素,则搜索列表的下半部分并比较其中间值。 将该列表重复分成两半,直到找到该元素或没有其他要搜索的项目为止。

    要在列表中搜索9:

    1 2 3 4 5 6 7 8 9 10

    我们首先找到中间元素。 这是位置Math.floor((first + last)/2)处的元素,其中first是第一个索引, last是最后一个索引。 我们选择四舍五入,以便如果结果为分数,则变为整数。 该列表的中间元素为5。我们的搜索值9大于5,因此我们搜索列表:

    6 7 8 9 10

    这部分的中间元素是8。9大于8,所以我们搜索列表:

    9 10

    中间元素是9,因此我们可以在此处停止搜索。

    这是一些表示上述用于二进制搜索的算法的伪代码:

    Set first to 0
    Set last to the last index in the list
    Set found to false
    Set position to −1
    while found is false and first is less than or equal to last
        Set middle to the index halfway between first and last
        if list[middle] equals the desired value
            Set found to true
            Set position to middle
        else if list[middle] is greater than the desired value
            Set last to middle − 1
        else
            Set first to middle + 1
    return position

    二进制搜索JavaScript实现

    现在,让我们用JavaScript编写二进制搜索算法!

    我们将创建一个函数binarySearch ,该函数接受一个值和一个数组作为参数。 如果找到,它将返回列表中值所在位置的索引。 如果找不到该值,则返回-1。 这是我们用JavaScript编写的实现:

    function binarySearch(value, list) {
        let first = 0;    //left endpoint
        let last = list.length - 1;   //right endpoint
        let position = -1;
        let found = false;
        let middle;
    
        while (found === false && first <= last) {
            middle = Math.floor((first + last)/2);
            if (list[middle] == value) {
                found = true;
                position = middle;
            } else if (list[middle] > value) {  //if in lower half
                last = middle - 1;
            } else {  //in in upper half
                first = middle + 1;
            }
        }
        return position;
    }

    结论

    在本教程中,我们看到了如何实现线性搜索和二进制搜索算法。 线性搜索算法更简单,不需要排序数组。 但是,与较大的数组一起使用时效率很低。 在最坏的情况下,该算法必须搜索所有进行n次比较的元素(其中n是元素数)。

    另一方面,二进制搜索算法要求您首先对数组进行排序,并且实现起来更加复杂。 但是,即使考虑分拣成本,它也更有效。 例如,具有10个元素的数组最多可以对二进制搜索进行4个比较,而对于线性搜索最多可以进行10个比较-并不是很大的改进。 但是,对于具有1,000,000个元素的数组,二进制搜索中最坏的情况是只有20个比较。 与线性搜索相比,这是一个巨大的进步!

    知道如何使用二进制搜索不仅是面试问题的练习内容。 这是一项实用技能,可以使您的代码更高效地工作。

    翻译自: https://code.tutsplus.com/tutorials/the-binary-search-algorithm-in-javascript--cms-30003

    展开全文
  • 动态二进制树搜索算法 二进制搜索树 (Binary Search Tree) A binary search tree is a useful data structure for fast addition and removal of data. 二进制搜索树是用于快速添加和删除数据的有用数据结构。 It...
  • 二进制树形搜索算法 二进制搜索用于在 值的排序列表 。 它选择排序值数组中的中间元素,并将其与目标值进行比较; 这就是我们在数组中寻找的关键。 如果它小于目标值,则在中间元素之后搜索,直到数组末尾。 如果...
  • 物联12:二进制树型搜索算法

    万次阅读 2015-04-15 10:43:49
     纯ALOHA算法和时隙ALOHA算法的信道最佳利用率为18.4%和36.8%,随着标签数量的增加,其性能急剧恶化,因此人们提出了二进制搜索算法。二进制防碰撞算法基于轮询的办法,按照二进制树模型和一定的顺序对所有的可能...
  •  二进制树型搜索算法由读写器控制,基本思想是不断的将导致 碰撞的电子标签进行划分,缩小下一步搜索的标签数量,直到只有 一个电子标签进行回应(即没有碰撞发生)。 二进制树型搜索算法实现步骤为:  【1】...
  • 但是我不会逐步解释算法,而是会深入了解二进制搜索的工作原理和使用方式。 如果您不知道Binary Search,请查看: geeksforgeeks.org/binary-search 。 给定一个已排序的数组,我们找到最中间的元素并使用键...
  • 提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 一、0-1背包问题 1、问题描述 2、数学模型 二 、二进制灰狼算法 1、引言 2、算法改进 3、数学模型 4、算法流程 三、源代码 四、运行...
  • 二进制搜索防碰撞算法中用的主要命令有: 1、Request(请求):阅读器向其识别区中的标签发送带有标签序列号的请求命令,标签接到命令后,其自身序列号小于或者等于该序列号的标签会将自己的序列号发送给阅读器,...
  • 提出一种基于模型的配电网故障诊断方案,该方案首先根据配电网原理模型的仿真数据和实际观测值存在的差异得到极小冲突集,然后由离散二进制粒子群优化算法推出可能的故障元件和故障形式,最后由贝叶斯方法确定概率...
  • 二进制树型搜索算法的实现步骤如下:  (1)读写器广播发送最大序列号查询条件Q,其作用范围内的标签在同一时刻传输它们的序列号至读写器。  (2)读写器对收到的标签进行响应,如果出现不一致
  • 讲述 离散二进制原理 ,以背包问题具体讲解离散二进制粒子群。代码语言:python、MATLAB。
  • 比如A: 10101010 B:10101000 读写器第一遍请求,得到的结果就是: 101010x0 这时候是直接得到两个标签的ID还是将x设为0再发送一次请求呢?
  • 在RFID防碰撞算法中,二进制算法是目前应用最广泛的一种。因为在算法执行过程中,读写器要多次发送命令给应答器,每次命令都把应答器分成两组,多...二进制树型搜索算法模型图如下图所示: 二进制树型搜索算法
  • RFID防碰撞 二进制树形搜索算法 C语言实现

    千次阅读 热门讨论 2018-04-01 20:31:13
    本篇文章只是简单的用C语言模拟出了二进制搜索算法的实现方法,但是并没有用到理论中的二叉树排序理论,所以并不是一个严格意义上的树形搜索算法 话不多说,先上一段A标签收到读写器发送的REQUEST命令的程序 if(a...
  • 讲解RFID二进制树和ALOHA防碰撞算法的基本原理
  • 图片来源于网络都知道计算机数据是以二进制数0和1补码的形式存储在内存中。那你知道它们转换关系吗?那么问题来了,为什么要转换?前面已经说过计算机数据是以二进制0和1存储,所以它们要转换为二进制存储在计算机中...
  •   二制树型搜索算法由读写器控制,基本思想是...二进制树型搜索算法的模型如图所示,其基本思想是将处于冲突的标签分成左 右两个子集0和1,先查询子集0,若没有冲突,则正确识别标签,若仍有冲突 则再分
  • RFID系统二进制数树型搜索算法是如何解决碰撞的?简述其实现步骤。 答:二进制树型搜索算法有读写器控制,基本思想是不断的将导致碰撞的 电子标签进行划分,缩小下一步搜索的标签数量,直到只有一个电子标签进行...
  • RFID-二进制搜索

    千次阅读 热门讨论 2019-06-16 22:28:22
    MATLAB编程实现二进制搜索与二分支搜索
  • 二进制搜索听起来很计算机,它有个接地气的名字叫二分法,是否瞬间清楚很多呢,顾名思义,二分法就是讲查找的东西分成两半后查找。 我们都用过新华字典,我使用的方法如下(比如查找“我”字): 将字典大约分成...
  • 题目:1000瓶药水,1瓶有毒药,服用后一小时...从0-7的顺序将三位的二进制数按顺序(如图)写出来,写好之后从横向看,三行就分配给三只老鼠,一代表是用这些瓶子的毒药做 了混合,零就是没有用到这些瓶子里的毒药。..
  • 这里写自定义目录标题原理: 实现语言:python 实验要求: (1)普通二进制树搜索: 设计一个1、11、21…标签数目 ...1.普通二进制搜索算法 二进制搜索技术以唯一的序列号来识别射频电子标签为基础。
  • 其基本思想是不断的将导致碰撞的电子标签进行划分,缩小下一步搜索的标签数量,直到没有发生碰撞。其具体实现步骤如下: 1、读写器广播发送最大序列号查询条件Q,其作用范围内的标签在同一时刻传输它们的序列号至...
  • 两个n位二进制数分别存储在两个n元数组A和B中,这两个整数的和存在一个n+1元的数组C中答:此问题主要是考察相加进位的问题,元素1+1 =0 并且往前进一位ADD-BINARY(A,B)C=new integer[A.length+1]carry=0for i=A....
  • 开博客的第一篇文章便是字典树实现模糊匹配,那个时候提到会把字典树导入二进制文件后进行搜索 优缺点比较: 对字典树的深搜实现模糊匹配: 缺点:每次启动程序需要加载一颗字典树,浪费时间,浪费空间。 优点:...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 42,873
精华内容 17,149
关键字:

二进制搜索算法原理