From 49611afcea26903e5c4482f912635e52cf63cabc Mon Sep 17 00:00:00 2001 From: Mert-Kayhan Ablachim Date: Thu, 26 Oct 2017 21:23:56 +0300 Subject: [PATCH] add documented jump search algorithm --- dsalglib/include/jumpsearch.h | 45 +++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 dsalglib/include/jumpsearch.h diff --git a/dsalglib/include/jumpsearch.h b/dsalglib/include/jumpsearch.h new file mode 100644 index 0000000..12609e4 --- /dev/null +++ b/dsalglib/include/jumpsearch.h @@ -0,0 +1,45 @@ +#ifndef DSALGLIB_KMPSEARCH_H +#define DSALGLIB_KMPSEARCH_H + +#include "array.h" + +namespace dsa +{ + template + long long int jumpsearch( array arr, type x) + { + // Finding block size to be jumped + long long int n = arr.size(); + long long int step = sqrt(n); + + // Finding the block where element is + // present (if it is present) + long long 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; + } + +} +#endif //DSALGLIB_KMPSEARCH_H \ No newline at end of file