Binary Search Algorithm in python

  • Binary Search algorithm finds the position of a specified input value (the search "key") within an array sorted by key value. 
  • For binary search, the array should be arranged in ascending or descending order. 
  • In each step, the algorithm compares the search key value with the key value of the middle element of the array. 
  • If the keys match, then a matching element has been found and its index, or position, is returned. 
  • Otherwise, if the search key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the search key is greater, on the sub-array to the right. 
  • If the remaining array to be searched is empty, then the key cannot be found in the array and a special "not found" indication is returned.


import math

def binary_search(numbers, value, index_low=None, index_high=None):
    if index_low is None: index_low = 0
    if index_high is None: index_high = len(numbers) - 1
        
    if index_low == index_high:
        if numbers[index_low] == value:
            return index_low
        else:
            return -1
            
    pivot = (index_low + index_high) / 2
    
    if numbers[pivot] > value:
        new_high = int(math.floor((index_high + index_low) / 2.0))
        return binary_search(numbers, value, index_low=index_low, index_high=new_high)
    elif numbers[pivot] < value:
        new_low = int(math.ceil((index_high + index_low) / 2.0))
        return binary_search(numbers, value, index_low=new_low, index_high=index_high)
    else:
        return pivot

if __name__ == "__main__":
    # Pre-sorted numbers
    numbers = [-100, -6, 0, 1, 5, 14, 15, 26, 99]
    value = 15
    
    # Print numbers to search
    print 'Numbers:'
    print ' '.join([str(i) for i in numbers])
    
    # Find the index of 'value'
    index = binary_search(numbers, value)

    # Print the index where 'value' is located
    print '\nNumber %d is at index %d' % (value, index)

No comments:

Post a Comment