diff --git a/searching/README.md b/searching/README.md index 06904348..7d0f9d01 100644 --- a/searching/README.md +++ b/searching/README.md @@ -4,6 +4,7 @@ 1. linear-search.cpp 2. binary-search.cpp +3. jump-search.cpp ### python diff --git a/searching/c-or-cpp/jump-search.cpp b/searching/c-or-cpp/jump-search.cpp new file mode 100644 index 00000000..cc452ce3 --- /dev/null +++ b/searching/c-or-cpp/jump-search.cpp @@ -0,0 +1,39 @@ +#include +#include +using namespace std; + +int jumpSearch(int arr[], int n, int key) +{ + int start = 0; + int end = sqrt(n); //the square root of array length + while (arr[end] <= key && end < n) + { + start = end; //if it is not correct block then shift block + end += sqrt(n); + if (end > n - 1) + end = n; //if right exceeds then bound the range + } + for (int pos = start; pos < end; pos++) + { //perform linear search + if (arr[pos] == key) + return pos; //the correct position of the key + } + return -1; // if element is not found +} + +int main() +{ + int n, key, loct; + cout << "Enter the length of arr:\n"; + cin >> n; + int arr[n]; + cout << "Enter the elements of arr:\n"; + for (int i = 0; i < n; i++) + cin >> arr[i]; // Taking input + cout << "Enter search key: "; + cin >> key; + if ((loct = jumpSearch(arr, n, key)) != -1) //Calling of jumpSearch function and getting a location back + cout << "Element found at location: " << loct << endl; + else + cout << "Element does not exist in the array." << endl; +} \ No newline at end of file