The binary lookup requires that the object must be ordered, with the following basic principles:
- Starting from the middle element of an array, the search process ends if the intermediate element is exactly the element to be found;
- 2. If a particular element is greater than or less than the middle element, it is found in the half of the array greater than or less than the middle element, and is compared with the beginning from the middle element.
- 3. If an array of steps is empty, the representation cannot be found.
Binary lookup also becomes binary lookup, where each comparison reduces the search scope by half, and its time complexity is O (LOGN).
Recursion not used:
1A = [1,5,-9,2,8]2 3Low =04High = Len (a)-15 defMid_sort (Array,value):#value to find6 7 while(Low <High ):8Mid = (Low+high)/29 Ten ifArray[mid] <Value: OneLow = Mid+1 A elifArray[mid] >Value: -High = Mid-1 - Else: the returnMid - - returnNone
Use recursion:
1 defBinary_search (array,value,low,high):2 ifLow>High :3 returnNone4Mid = (low + high)/25 ifArray[mid] >Value:6 returnBinary_search (array,value,low,mid-1)7 elifArray[mid] <Value:8 returnBinary_search (array,value,mid+1, High)9 Else:Ten returnMid
Performance
High recursive efficiency with non-recursive recursion
Python Two-point lookup