binary search algorithm

binary search

 Starting from the candidate area data[0:n] of the ordered list, the candidate area can be reduced by half by comparing the value to be searched with the intermediate value of the candidate area

 
Binary search:
In a range of numbers, find the middle value, and judge the comparison between the value you are looking for and the middle value.
If the middle value is larger, continue to search in the area to the left of the middle value as above.
If the middle value is smaller, continue to search as above in the area to the right of the middle value.
until we find the number we want.
 
l = [1,3,4,5,6,7,44,55,77,88,99 ]
 def func(line,num):
    low =0 #Get the minimum subscript 
    high=len(line)-1 #Get the maximum subscript 
    while low <= high: #Only the minimum subscript is less than the maximum subscript to prove that there is data 
        mid=(low+high)//2 #Get the middle subscript to achieve bisection 
        if line[mid] == num: #If the middle number is equal to the value you want to find 
            return mid #Return the subscript 
        elif   line[mid] > num: #If the value is greater than you want The value to be searched for 
            high=mid-1 #Shift the middle subscript to the left by one place as the value of the largest subscript to reduce the search range by half 
        else :
            low =mid+1 #Similarly , the minimum subscript is shifted to the right 
    return  " error " 
print (func(l,1 ))

# output 
0

 

Guess you like

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