Python/searches/jump_search.py
Christian Clauss bfcb95b297
Create codespell.yml (#1698)
* fixup! Format Python code with psf/black push

* Create codespell.yml

* fixup! Format Python code with psf/black push
2020-01-18 13:24:33 +01:00

27 lines
590 B
Python

import math
def jump_search(arr, x):
n = len(arr)
step = int(math.floor(math.sqrt(n)))
prev = 0
while arr[min(step, n) - 1] < x:
prev = step
step += int(math.floor(math.sqrt(n)))
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
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)}")