-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.py
More file actions
executable file
·55 lines (39 loc) · 1.12 KB
/
binarysearch.py
File metadata and controls
executable file
·55 lines (39 loc) · 1.12 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#/usr/bin/python
#-*- coding:utf-8 -*-
def BinarySearch(arr, size, target):
low, high = 0, size-1
while low <= high:
mid = (low+high)/2
if target == arr[mid]: return mid
elif target < arr[mid]:
high = mid - 1
else:
low = mid + 1
return -1
def AdvancedBinarySearch(arr, size, target):
low, high = 0, size-1
while low <= high:
mid = (low+high)/2
if target == arr[mid]:
i = j = mid
return (i, j, mid)
elif target < arr[mid]:
high = mid - 1
else:
low = mid + 1
i = -1 if target <= arr[0] else high
j = -1 if target >= arr[size-1] else low
return (i, j, -1)
if __name__ == "__main__":
import random
array = list()
for i in range(10):
array.append(random.randint(0, 100))
array.sort()
for element in array:
print element,
target = input("\ntarget:")
# position = BinarySearch(array, len(array), target)
result = AdvancedBinarySearch(array, len(array), target)
# print "not found" if position == -1 else "Position:",position
print "not found.\nmax:%s\nmin:%s" % (result[0], result[1]) if result[2] == -1 else "found.\nposition:%s" % result[2]