From bbe7fc3198b73d3b392d4e57af74838235795b00 Mon Sep 17 00:00:00 2001 From: sourav singh <68277063+sourav9582@users.noreply.github.com> Date: Wed, 5 Oct 2022 14:00:50 +0530 Subject: [PATCH] jump search MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Time Complexity : O(√n) Auxiliary Space : O(1) --- Jump Search | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Jump Search diff --git a/Jump Search b/Jump Search new file mode 100644 index 0000000..bb91219 --- /dev/null +++ b/Jump Search @@ -0,0 +1,48 @@ +//Jump Search is a searching algorithm for sorted arrays +//suppose we have an array arr[] of size n and a block (to be jumped) of size m. +//Then we search in the indexes arr[0], arr[m], arr[2m]…..arr[km] and so on. +//Once we find the interval (arr[km] < x < arr[(k+1)m]), +//we perform a linear search operation from the index km to find the element x +#include +using namespace std; + +int jumpSearch(int arr[], int x, int n) +{ + int step = sqrt(n); + int prev = 0; + while (arr[min(step, n)-1] < x) + { + prev = step; + step += sqrt(n); + if (prev >= n) + return -1; + } + + while (arr[prev] < x) + { + prev++; + + if (prev == min(step, n)) + return -1; + } + + if (arr[prev] == x) + return prev; + + return -1; +} + + +int main() +{ + int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, + 34, 55, 89, 144, 233, 377, 610 }; + int x = 55; + int n = sizeof(arr) / sizeof(arr[0]); + + + int index = jumpSearch(arr, x, n); + + cout << "\nNumber " << x << " is at index " << index; + return 0; +}