Skip to main content
Tweeted twitter.com/#!/StackCodeReview/status/639942716172955648
added 264 characters in body
Source Link
CodeYogi
  • 5.1k
  • 12
  • 50
  • 104

The given code find the minimum element in a sorted array rotated by some fixed distance. Eg: [1, 2, 3, 4, 5, 6, 7] -> [3, 4, 5, 6, 7, 1, 2]

The elements in the array are all unique. Just wanted to check if the code handles all edge cases and is correct.

def findMin(ary):
    
    def recurse(lo, hi):
        # Base cases   
        if (ary[lo] < ary[hi]):
            return ary[lo]
        if (hi - lo == 1):
            return min(ary)

        mid = lo + (hi - lo) / 2
        if (ary[mid] < ary[hi]):
            return recurse(lo, mid)
        else:
            return recurse(mid, hi)
            
    return recurse(0, len(ary) - 1)


ary = (3, 4, 5, 6, 7, 1, 2)
print findMin(ary) # 1
def findMin(ary):
    
    def recurse(lo, hi):
        # Base cases   
        if (ary[lo] < ary[hi]):
            return ary[lo]
        if (hi - lo == 1):
            return min(ary)

        mid = lo + (hi - lo) / 2
        if (ary[mid] < ary[hi]):
            return recurse(lo, mid)
        else:
            return recurse(mid, hi)
            
    return recurse(0, len(ary) - 1)


ary = (3, 4, 5, 6, 7, 1, 2)
print findMin(ary) # 1

The given code find the minimum element in a sorted array rotated by some fixed distance. Eg: [1, 2, 3, 4, 5, 6, 7] -> [3, 4, 5, 6, 7, 1, 2]

The elements in the array are all unique. Just wanted to check if the code handles all edge cases and is correct.

def findMin(ary):
    
    def recurse(lo, hi):
        # Base cases   
        if (ary[lo] < ary[hi]):
            return ary[lo]
        if (hi - lo == 1):
            return min(ary)

        mid = lo + (hi - lo) / 2
        if (ary[mid] < ary[hi]):
            return recurse(lo, mid)
        else:
            return recurse(mid, hi)
            
    return recurse(0, len(ary) - 1)


ary = (3, 4, 5, 6, 7, 1, 2)
print findMin(ary) # 1
Source Link
CodeYogi
  • 5.1k
  • 12
  • 50
  • 104

Find minimum in rotated sorted array

def findMin(ary):
    
    def recurse(lo, hi):
        # Base cases   
        if (ary[lo] < ary[hi]):
            return ary[lo]
        if (hi - lo == 1):
            return min(ary)

        mid = lo + (hi - lo) / 2
        if (ary[mid] < ary[hi]):
            return recurse(lo, mid)
        else:
            return recurse(mid, hi)
            
    return recurse(0, len(ary) - 1)


ary = (3, 4, 5, 6, 7, 1, 2)
print findMin(ary) # 1