-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearch Methods.py
More file actions
54 lines (39 loc) · 1.43 KB
/
Search Methods.py
File metadata and controls
54 lines (39 loc) · 1.43 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
def linearSearch(numberList, numberToFind):
for index, number in enumerate(numberList):
if number == numberToFind:
return index
return -1
def binarySearch(numberList, numberToFind):
midIndex = int((len(numberList) - 1)/2)
mid = numberList[midIndex]
if numberToFind == mid:
return midIndex
elif numberToFind > mid:
return len(numberList[0:midIndex+1]) + binarySearch(numberList[midIndex+1:], numberToFind)
elif numberToFind < mid:
return binarySearch(numberList[0:midIndex], numberToFind)
else:
return -1
def findAllOccurences(numberList, numberToFind):
index = binarySearch(numberList, numberToFind)
indexList = [index]
lIndex = index - 1
while lIndex >= 0:
if numberList[lIndex] == numberToFind:
indexList.append(lIndex)
else:
break
lIndex = lIndex - 1
rIndex = index + 1
while rIndex <= len(numberList) - 1:
if numberList[rIndex] == numberToFind:
indexList.append(rIndex)
else:
break
rIndex = rIndex + 1
return indexList
if __name__ == '__main__':
rollList = [1, 2, 3, 6, 8, 10, 15, 15, 15, 90, 103, 110, 130, 150]
print(linearSearch(rollList, 15))
print(binarySearch(rollList, 15))
print(findAllOccurences(rollList, 15)) #find one occurrence using binary search, then iteratively search right and left of the element