-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinarySearch.py
48 lines (35 loc) · 1.18 KB
/
binarySearch.py
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
import json, time
startTimeLinearSearch = time.time()
startTimeBinarySearch = time.time()
# loads a large dataset to make tests
fileDatasetName = "list.json"
searchIndexValue = 0
f = open(fileDatasetName)
fileData = json.load(f)
dataListToTest = fileData["metadata"]
def linearSearch(value, list):
for index, val in enumerate(list):
if value == val:
print("--- %s seconds ---" % (time.time() - startTimeBinarySearch))
return index
print("--- %s seconds ---" % (time.time() - startTimeBinarySearch))
return index
def binarySearch(searchItem, list):
low = 0
high = len(list) - 1
while low <= high:
mid = (high + low) // 2
if list[mid] == searchItem:
print("--- %s seconds ---" % (time.time() - startTimeLinearSearch))
return mid
else:
if searchItem > list[mid]:
low = mid + 1
else:
high = mid - 1
print("--- %s seconds ---" % (time.time() - startTimeLinearSearch))
return -1
size = len(dataListToTest)
print(f"List size: {size}")
# binarySearch(searchIndexValue, dataListToTest)
# linearSearch(searchIndexValue, dataListToTest)