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; +}