Binary Search
Okay, so how do you think we can search for a paticular element in an array?
One obvious way will be to loop through the array and return true at which the element is found and to return false if it doesn't exist in the array. But the problem with this algorithm known as linear search is that it can very quickly turn out to be very costly in terms of space and time as this algorithm takes O(n) or linear time. This turns out to be highly costly for a large number of elements in an array.
#Linear Search -->
def linear_search(array , n ):
  for i in array:
    if i == n :
      return True
#Binary Search --> 
def binary_search(array, n ):
  #Setting up search space variables and found flag
  high = len(a) - 1 
  low  = 0          
  found = False
  #search begins from while loop
  while( first <= last and not found ):
    #calculating midpoint
    mid = (low + high) // 2
    #check if element at midpoint is equal to the element being searched
    if array[mid] == n :
      return True
    else :
      if item < array[midpoint] :
      # if item is larger than the item at midpoint then the search space is cut into half
        high = midpoint - 1
      else :
        #if item is larger than the item at midpoint, low is set to be the index next to midpoint
        low = midpoint + 1
  return found
Comments
Post a Comment