Python binary search thinking and understanding Xiaobaixiang け

First, let’s talk about the idea of ​​binary search. This is a course for Xiaobai, big brother, please give in, thank you

Given an ordered sequence (must be sorted) such as [1,2,3,4,5,6,7,8,9,10,20,30,400], then we query the coordinates where an element occurs Position, the default is 0 to start.

For example, we query the location where 20 appears.

First, get the total number of elements [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 400], 13 elements, and then get the first and last subscripts of the elements 0 and 13

Then the binary search, also known as the halved search, as the name implies, is the search of half and half, then we divide the above elements into two parts, and if there is a decimal, round down (the use of math.foor) (0+13)/2 =6

So we determined that the middle coordinate is 6, and we got two intervals [0,6] [7,13] This is an interval of array positions, and then we are to compare the two intervals separately.

Compare the left part first. [01,2,3,4,5,6]=The corresponding element is [1,2,3,4,5,6,7] Compare whether the largest element is less than the current element 20 We find that the largest is 7,7<20 , so we discard the left part.

ok, the following is the right part [8, 9, 10, 20, 30, 400], now we will perform a binary operation on the remaining right half to get two pieces of data [8, 9, 10] and [20, 30, 400]

The same operation discards the left half and continues to operate the right half, [20, 30, 400] learns that [20] [30, 40] Well, we get the final number 20.

 

when comparing 

The maximum number compared on the left is less than the specified number, and the minimum number compared on the right is greater than the specified number. The text is too wordy to read the picture.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324684874&siteId=291194637