From 60cd714c8924fafd10b69e77232d205aa14283f6 Mon Sep 17 00:00:00 2001 From: Aks1307 <40080782+Aks1307@users.noreply.github.com> Date: Tue, 2 Oct 2018 00:02:36 +0530 Subject: [PATCH] jumpSearch.cpp --- searching/jumpSearch.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 searching/jumpSearch.cpp diff --git a/searching/jumpSearch.cpp b/searching/jumpSearch.cpp new file mode 100644 index 0000000..d8279cf --- /dev/null +++ b/searching/jumpSearch.cpp @@ -0,0 +1,36 @@ +#include +using namespace std; + +int jumpSearch(int arr[], int x, int n) +{ + // Finding block size to be jumped + int step = sqrt(n); + + // Finding the block where element is + // present (if it is present) + int prev = 0; + while (arr[min(step, n)-1] < x) + { + prev = step; + step += sqrt(n); + if (prev >= n) + return -1; + } + + // Doing a linear search for x in block + // beginning with prev. + while (arr[prev] < x) + { + prev++; + + // If we reached next block or end of + // array, element is not present. + if (prev == min(step, n)) + return -1; + } + // If element is found + if (arr[prev] == x) + return prev; + + return -1; +}