Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions Jump_Search_Algo/JumpSearch.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* C++ program to implement Jump Search.
*
* Jump Search is a searching algorithm for sorted arrays.
* The basic idea is to check fewer elements (than linear search)
* by jumping ahead by fixed steps.
*/

#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>

int jumpSearch(const std::vector<int>& arr, int x) {
int n = arr.size();

// Finding block size to be jumped
int step = std::sqrt(n);

// Finding the block where element is
// present (if it is present)
int prev = 0;
while (arr[std::min(step, n) - 1] < x) {
prev = step;
step += std::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 == std::min(step, n))
return -1;
}

// If element is found
if (arr[prev] == x)
return prev;

return -1;
}

// Main function to test the algorithm
int main() {
std::vector<int> arr = {0, 1, 1, 2, 3, 5, 8, 13, 21,
34, 55, 89, 144, 233, 377, 610};
int x = 55;

// Find the index of 'x' using Jump Search
int index = jumpSearch(arr, x);

if (index != -1) {
std::cout << "Number " << x << " is at index " << index << std::endl;
} else {
std::cout << "Number " << x << " is not in the array" << std::endl;
}

x = 7;
index = jumpSearch(arr, x);

if (index != -1) {
std::cout << "Number " << x << " is at index " << index << std::endl;
} else {
std::cout << "Number " << x << " is not in the array" << std::endl;
}

return 0;
}