2019-10-23 02:36:21 +08:00
|
|
|
// C++ program to implement Jump Search
|
|
|
|
|
2020-05-27 04:40:09 +08:00
|
|
|
#include <algorithm>
|
|
|
|
#include <cmath>
|
|
|
|
#include <iostream>
|
2019-10-23 02:36:21 +08:00
|
|
|
|
2020-05-27 04:40:09 +08:00
|
|
|
int jumpSearch(int arr[], int x, int n) {
|
2019-10-23 02:36:21 +08:00
|
|
|
// Finding block size to be jumped
|
2020-05-27 04:40:09 +08:00
|
|
|
int step = std::sqrt(n);
|
2019-10-23 02:36:21 +08:00
|
|
|
|
|
|
|
// Finding the block where element is
|
|
|
|
// present (if it is present)
|
|
|
|
int prev = 0;
|
2020-05-27 04:40:09 +08:00
|
|
|
while (arr[std::min(step, n) - 1] < x) {
|
2019-10-23 02:36:21 +08:00
|
|
|
prev = step;
|
2020-05-27 04:40:09 +08:00
|
|
|
step += std::sqrt(n);
|
|
|
|
if (prev >= n) return -1;
|
2019-10-23 02:36:21 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Doing a linear search for x in block
|
|
|
|
// beginning with prev.
|
2020-05-27 04:40:09 +08:00
|
|
|
while (arr[prev] < x) {
|
2019-10-23 02:36:21 +08:00
|
|
|
prev++;
|
|
|
|
|
|
|
|
// If we reached next block or end of
|
|
|
|
// array, element is not present.
|
2020-05-27 04:40:09 +08:00
|
|
|
if (prev == std::min(step, n)) return -1;
|
2019-10-23 02:36:21 +08:00
|
|
|
}
|
|
|
|
// If element is found
|
2020-05-27 04:40:09 +08:00
|
|
|
if (arr[prev] == x) return prev;
|
2019-10-23 02:36:21 +08:00
|
|
|
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Driver program to test function
|
2020-05-27 04:40:09 +08:00
|
|
|
int main() {
|
|
|
|
int arr[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610};
|
2019-10-23 02:36:21 +08:00
|
|
|
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
|
2020-05-27 04:40:09 +08:00
|
|
|
std::cout << "\nNumber " << x << " is at index " << index;
|
2019-10-23 02:36:21 +08:00
|
|
|
return 0;
|
|
|
|
}
|