From 73d25324df1eef33849b2b29c454ba0818afff8a Mon Sep 17 00:00:00 2001 From: Rishu-Xingh007 <54987394+Rishu-Xingh007@users.noreply.github.com> Date: Thu, 17 Oct 2019 19:42:53 +0530 Subject: [PATCH] Create Jump_search.cpp --- Jump_search.cpp | 56 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Jump_search.cpp diff --git a/Jump_search.cpp b/Jump_search.cpp new file mode 100644 index 0000000..ed93e01 --- /dev/null +++ b/Jump_search.cpp @@ -0,0 +1,56 @@ +// C++ program to implement Jump Search + +#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; +} + +// Driver program to test function +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]); + + // Find the index of 'x' using Jump Search + int index = jumpSearch(arr, x, n); + + // Print the index where 'x' is located + cout << "\nNumber " << x << " is at index " << index; + return 0; +} + +// Contributed by nuclode