forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
last_occurance.py
47 lines (42 loc) · 1.41 KB
/
last_occurance.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
#
# Find last occurance of a number in a sorted array (increasing order)
# Approach- Binary Search
# T(n)- O(log n)
#
def lastOccurance(array, query):
lo, hi = 0, len(array) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if (array[mid] == query and mid == len(array)-1) or \
(array[mid] == query and array[mid+1] > query):
return mid
elif (array[mid] <= query):
lo = mid + 1
else:
hi = mid - 1
def main():
array = [1, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6, 6, 6]
print(array)
print("-----SEARCH-----")
query = 3
print("found last: ", query, " in index:", lastOccurance(array, query))
print("-----SEARCH-----")
query = 5
print("found last: ", query, " in index:", lastOccurance(array, query))
print("-----SEARCH-----")
query = 7
print("found last: ", query, " in index:", lastOccurance(array, query))
print("-----SEARCH-----")
query = 1
print("found last: ", query, " in index:", lastOccurance(array, query))
print("-----SEARCH-----")
query = -1
print("found last: ", query, " in index:", lastOccurance(array, query))
print("-----SEARCH-----")
query = 9
print("found last: ", query, " in index:", lastOccurance(array, query))
print("-----SEARCH-----")
query = 6
print("found last: ", query, " in index:", lastOccurance(array, query))
if __name__ == "__main__":
main()