From 76c9e1135d705a55091675fb0d5551a525c64ce5 Mon Sep 17 00:00:00 2001 From: chawlaj100 Date: Thu, 1 Oct 2020 01:57:05 +0530 Subject: [PATCH] Added searching scripts --- Exponential_Search.py | 33 +++++++++++++++++++++++++++++++++ Jump_Search.py | 26 ++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 Exponential_Search.py create mode 100644 Jump_Search.py diff --git a/Exponential_Search.py b/Exponential_Search.py new file mode 100644 index 0000000..eadcea7 --- /dev/null +++ b/Exponential_Search.py @@ -0,0 +1,33 @@ +num = int(input("Please enter size of array : ")) +arr_str = list(input().split(" ")) +if len(arr_str)!=num: + print("Please enter only "+str(num)+" elements.") + exit() +arr = list(map(int, arr_str)) +val = int(input("Enter value to be found : ")) + +def binary_search(arr, l, r, val): + if r >= l: + mid = int((l + (r)) / 2) + + if arr[mid] == val: + return mid + if arr[mid] < val: + binary_search(arr, mid+1, r, val) + else: + binary_search(arr, l, mid-1, val) + return -1 + +def exponent(arr, n, val): + if arr[0] == val: + return 0 + + i = 1 + while i < n and arr[i] <= val : + i *= 2 + + index = binary_search(arr, i/2, min(i,n), val) + return index + +index = exponent(arr, len(arr), val) +print(str(val)+" is positioned at : "+str(index+1)) \ No newline at end of file diff --git a/Jump_Search.py b/Jump_Search.py new file mode 100644 index 0000000..dd80255 --- /dev/null +++ b/Jump_Search.py @@ -0,0 +1,26 @@ +import math +num = int(input("Please enter size of array : ")) +arr_str = list(input().split(" ")) +if len(arr_str)!=num: + print("Please enter only "+str(num)+" elements.") + exit() +arr = list(map(int, arr_str)) +val = int(input("Enter value to be found : ")) + +def jump_search(arr, n, val): + prev = 0 + step = int(math.sqrt(n)) + while arr[step] < val : + prev = step + step += int(math.sqrt(n)) + if prev >= n : + return -1 + else: + pass + + for i in range(prev, step): + if arr[i] == val: + return i + +index = jump_search(arr, len(arr), val) +print(str(val)+" is positioned at : "+str(index+1)) \ No newline at end of file