Learn To Solve It

  • C Programming
  • Python Programming

Table of Contents

  • Binary Search
    • Question
    • Solution
      • Explanation
On this page
  • Question
  • Solution
    • Explanation

Binary Search#

Question#

Implement and demonstrate the Binary search algorithm.

Solution#

import random

def find_in_sorted(arr, x):
    def binsearch(start, end):
        if start == end:
            return -1
        mid = start + (end - start) // 2
        if x < arr[mid]:
            return binsearch(start, mid)
        elif x > arr[mid]:
            return binsearch(mid+1, end)
        else:
            return mid
    return binsearch(0, len(arr))


ar = sorted(random.sample(list(range(10)),9))
r = random.randint(0,10)
print((find_in_sorted(ar,r)))

Explanation#

See also

  • Suggest a Code Improvement:algorithm_binary_search.py

  • Suggest a better explanation for algorithm_binary_search.rst

previous

Binary Representation

next

Cellular Automata

© Copyright 2022, Senthil Kumaran.

Created using Sphinx 4.5.0.