From 1ff7ff348c09ca6e7f764ec476b7e5d68c3a0a92 Mon Sep 17 00:00:00 2001 From: Anupam Baranwal <66070470+anupam-b@users.noreply.github.com> Date: Tue, 26 Jan 2021 17:33:56 +0530 Subject: [PATCH] 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. --- searching/README.md | 1 + searching/python/jump-search.py | 49 +++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 searching/python/jump-search.py diff --git a/searching/README.md b/searching/README.md index 0f682034..786633bd 100644 --- a/searching/README.md +++ b/searching/README.md @@ -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 diff --git a/searching/python/jump-search.py b/searching/python/jump-search.py new file mode 100644 index 00000000..5721ed3b --- /dev/null +++ b/searching/python/jump-search.py @@ -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!") \ No newline at end of file