Binary Search without Sorting

Consider the following binary search code in Python :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def binary_search(L,x):
    lo = 0
    hi = len(L) - 1
    while lo <= hi:
        mid = (lo + hi) / 2

        if L[mid] == x:
            return True
        elif L[mid] > x:
            hi = mid - 1
        elif L[mid] < x:
            lo = mid + 1
    return False

It works perfectly, unless if you forgot to sort L L in the first place! Given that L L is a permutation of 0 to 6 and x x is an integer in L L , how many distinct inputs ( L , x ) (L,x) are there such that the code still works?


The answer is 15120.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Kumar Edward
Nov 21, 2017
1
2
3
4
5
6
7
from itertools import permutations
cnt=0
for p in permutations(range(0,7)):
    for x in range(0,7):
        if binary_search(p,x):
            cnt+=1
print(cnt) 

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...