prepbook
  • Introduction
  • Some common stuff
    • python __repr__
    • HackerRank input tips
  • Data Structures and Algorithms
    • Breadth first search
    • Depth First Search
    • Dijkstra
    • A* Search Algorithm
    • Binary Search
    • python counter
    • Sorting
      • Merge Sort
      • Quick Sort
    • Priority Queue
  • Multiprocessing vs Threading
  • Common Coding
    • Find loop in lin list
    • Maximum sum subarray
  • Coding
    • Valid palindrome
    • Palindrome number
    • Remove duplicates from sorted array
    • Island perimeter
    • Serialize and Deserialize Binary Tree
    • Valid Soduku
    • Word Pattern
    • Word Pattern II
    • Group Anagrams
    • Implement Trie
    • Deep copy list with random node
    • Palindrome Permutation
    • Combination Sum
    • Clone Graph
    • Generate parenthesis
    • Fibonacci Number
    • LRU Cache
    • Merge two sorted arrays in place
    • Hamming Distance
    • Merge K sorted arrays
    • Kth smalles element in BST
    • Kth largest element in an array
    • Remove duplicates from sorted list
    • Power of 2
    • Nested list weight sum
    • SIngle number in a list
    • Factor combinations
    • Delete node from BST
  • hacker Rank
    • Coding
      • print staircase
      • Drawing book
      • Challenge 0
      • Min-Max sum
  • WorkRelatedCoding
    • Rectangle Overlap
  • Python tips
Powered by GitBook
On this page

Was this helpful?

  1. Data Structures and Algorithms

Binary Search

Listing two variants: One recursive and one iterative

# In this recursive version we are just not returning True/False. We are returning the index position 
# of the array where the match happened. We are using a global variable to note this index

idx = -1
def binSearch(V, arr, first, last):

    global idx
    mid = (first + last) / 2
    #print arr, first, last, mid

    if V == arr[mid]:
        #print 'found: ', mid
        idx = mid
        return mid

    if V < arr[mid]:
        binSearch(V, arr, 0, mid)
    if V > arr[mid]:
        binSearch(V, arr, mid+1, len(arr) - 1)
def binSearchIterative(V, arr):

    first = 0
    last = len(arr) - 1 
    found = False
    mid = -1

    while first <= last and not found:        
        mid = (first + last)/2

        if V == arr[mid]:
            found = True
        elif V < arr[mid]:
            last = mid - 1
        else:
            first = mid + 1

    #print 'found mid: ', mid
    print mid
PreviousA* Search AlgorithmNextpython counter

Last updated 5 years ago

Was this helpful?