Add jump search py (#29)

* Create jump-search.py

Added python implement jump search algorithm

* Update README.md

Updated README.md

* Updated jump-search.py

Added a check for sorted list in jump-search.
pull/31/head
Anupam Baranwal 2021-01-26 17:33:56 +05:30 committed by GitHub
parent c5538df596
commit 1ff7ff348c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 50 additions and 0 deletions

View File

@ -10,6 +10,7 @@
1. [Linear Search](python/linear-search.py)
2. [Binary Search](python/binary-search.py)
3. [Jump Search](python/jump-search.py)
### JavaScript

View File

@ -0,0 +1,49 @@
"""
Jump search algorithm iterates through a sorted list with a step of n^(1/2),
until the element compared is bigger than the one searched.If the item is not
in the particular step, it shifts the entire step.
It will then perform a linear search on the step until it matches the target.
If not found, it returns -1.
Time Complexity: O(n)
Space Complexity: O(1)
"""
import math
def jump_search(arr: list, x: int) -> int:
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
def check_sort(test: list) -> bool:
"""checks whether the given list is sorted or not."""
if sorted(test) == test:
return True
else:
return False
if __name__ == "__main__":
arr = [0, 1, 2, 8, 13, 17, 19, 25, 31, 32, 42]
target = 25
if check_sort(arr):
res = jump_search(arr, target)
if res == -1:
print("Number not found!")
else:
print(f"Number {target} is at index {res}")
else:
print("Given list is not sorted!")