-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathBinarySearch.py
More file actions
39 lines (32 loc) · 789 Bytes
/
BinarySearch.py
File metadata and controls
39 lines (32 loc) · 789 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import random
def InsertionSort(A, n):
for j in range(1, n):
key = A[j]
# Insert A[j] into the sorted sequence[1...j-1]
i = j - 1
while i >= 0 and A[i] > key:
A[i + 1] = A[i]
i = i - 1
A[i + 1] = key
return A
def BinarySearch(A, p, r, key):
if p >= r:
return -1
q = (p + r) / 2
if A[q] == key:
return q
elif A[q] < key:
return BinarySearch(A, q + 1, r, key)
else:
return BinarySearch(A, p, q, key)
# Pre procedure.
A = []
s = random.randint(5, 100)
for i in range(0, s):
A.append(random.randint(0, 1000))
A = InsertionSort(A, len(A))
key = random.choice(A)
print "Now displaying BinarySearch."
print A
print key
print BinarySearch(A, 0, len(A) - 1, key)