From 273f629450a41105748926fa6a4f07f7ccaf861f Mon Sep 17 00:00:00 2001 From: Shooman Khatri <112597601+ShoomanKhatri@users.noreply.github.com> Date: Mon, 14 Oct 2024 10:29:30 +0000 Subject: [PATCH] add: added programss on searching python --- Searching/Python/Jump_search.py | 35 +++++++++++++++++++++++++++++++ Searching/Python/Linear_search.py | 18 ++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 Searching/Python/Jump_search.py create mode 100644 Searching/Python/Linear_search.py diff --git a/Searching/Python/Jump_search.py b/Searching/Python/Jump_search.py new file mode 100644 index 0000000..a08511f --- /dev/null +++ b/Searching/Python/Jump_search.py @@ -0,0 +1,35 @@ +import math + +# Jump Search Function +def jump_search(arr, x): + length = len(arr) + step = int(math.sqrt(length)) + prev = 0 + + while arr[min(step, length) - 1] < x: + prev = step + step += int(math.sqrt(length)) + if prev >= length: + return -1 # Element not found + + # Perform linear search in the block + while arr[prev] < x: + prev += 1 + if prev == min(step, length): + return -1 # Element not found + + if arr[prev] == x: + return prev + return -1 + +# Data +arr = [2, 5, 6, 7, 8] +x = 6 + +# Function call +result = jump_search(arr, x) + +if result != -1: + print("Element is present at index", str(result)) +else: + print("Element is not present in array") diff --git a/Searching/Python/Linear_search.py b/Searching/Python/Linear_search.py new file mode 100644 index 0000000..142097c --- /dev/null +++ b/Searching/Python/Linear_search.py @@ -0,0 +1,18 @@ +# Linear Search Function +def linear_search(arr, x): + for index, value in enumerate(arr): + if value == x: + return index # Element found + return -1 # Element not found + +# Data +arr = [5, 8, 6, 7, 2] +x = 6 + +# Function call +result = linear_search(arr, x) + +if result != -1: + print("Element is present at index", str(result)) +else: + print("Element is not present in array")