document jump search

This commit is contained in:
Krishna Vedala 2020-05-28 20:36:44 -04:00
parent 4bc199ff1d
commit 2b57d1ff88
No known key found for this signature in database
GPG Key ID: BA19ACF8FC8792F7

View File

@ -1,9 +1,14 @@
// C++ program to implement Jump Search /**
* \file
* \brief C++ program to implement [Jump
* Search](https://en.wikipedia.org/wiki/Jump_search)
*/
#include <algorithm> #include <algorithm>
#include <cmath> #include <cmath>
#include <iostream> #include <iostream>
/** jump search implementation
*/
int jumpSearch(int arr[], int x, int n) { int jumpSearch(int arr[], int x, int n) {
// Finding block size to be jumped // Finding block size to be jumped
int step = std::sqrt(n); int step = std::sqrt(n);
@ -14,7 +19,8 @@ int jumpSearch(int arr[], int x, int n) {
while (arr[std::min(step, n) - 1] < x) { while (arr[std::min(step, n) - 1] < x) {
prev = step; prev = step;
step += std::sqrt(n); step += std::sqrt(n);
if (prev >= n) return -1; if (prev >= n)
return -1;
} }
// Doing a linear search for x in block // Doing a linear search for x in block
@ -24,10 +30,12 @@ int jumpSearch(int arr[], int x, int n) {
// If we reached next block or end of // If we reached next block or end of
// array, element is not present. // array, element is not present.
if (prev == std::min(step, n)) return -1; if (prev == std::min(step, n))
return -1;
} }
// If element is found // If element is found
if (arr[prev] == x) return prev; if (arr[prev] == x)
return prev;
return -1; return -1;
} }