2017-10-12 09:10:15 +00:00
|
|
|
import math
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
|
2017-10-12 09:10:15 +00:00
|
|
|
def jump_search(arr, x):
|
|
|
|
n = len(arr)
|
2018-04-13 01:56:40 +00:00
|
|
|
step = int(math.floor(math.sqrt(n)))
|
2017-10-12 09:10:15 +00:00
|
|
|
prev = 0
|
2019-10-05 05:14:13 +00:00
|
|
|
while arr[min(step, n) - 1] < x:
|
2017-10-12 09:10:15 +00:00
|
|
|
prev = step
|
2018-04-13 01:56:40 +00:00
|
|
|
step += int(math.floor(math.sqrt(n)))
|
2017-10-12 09:10:15 +00:00
|
|
|
if prev >= n:
|
|
|
|
return -1
|
|
|
|
|
|
|
|
while arr[prev] < x:
|
|
|
|
prev = prev + 1
|
|
|
|
if prev == min(step, n):
|
|
|
|
return -1
|
|
|
|
if arr[prev] == x:
|
|
|
|
return prev
|
|
|
|
return -1
|
|
|
|
|
|
|
|
|
2020-01-18 12:24:33 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
arr = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
|
|
|
|
x = 55
|
|
|
|
print(f"Number {x} is at index {jump_search(arr, x)}")
|