Jump Search in C++
Jump Search Algorithm in C++ (Complete Implementation).
1#include <iostream>2#include <cmath>3using namespace std;45int jumpSearch(int arr[], int n, int key) {6 // Calculate jump size7 int step = sqrt(n);8 int prev = 0;910 // Find the block where element might be11 while (arr[min(step, n) - 1] < key) {12 prev = step;13 step += sqrt(n);14 if (prev >= n) {15 return -1; // Element not found16 }17 }1819 // Perform linear search in the block20 while (arr[prev] < key) {21 prev++;22 if (prev == min(step, n)) {23 return -1; // Element not found24 }25 }2627 // If element is found28 if (arr[prev] == key) {29 return prev;30 }3132 return -1; // Element not found33}3435int main() {36 int arr[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610};37 int n = sizeof(arr) / sizeof(arr[0]);38 int key;3940 cout << "Sorted array: ";41 for (int i = 0; i < n; i++) {42 cout << arr[i] << " ";43 }44 cout << endl;4546 cout << "Enter element to search: ";47 cin >> key;4849 int result = jumpSearch(arr, n, key);5051 if (result != -1) {52 cout << "Element found at index: " << result << endl;53 } else {54 cout << "Element not found in array" << endl;55 }5657 return 0;58}
Output
Sorted array: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 Enter element to search: 55 Element found at index: 10
What's going on
The program searches for an element in a sorted array using Jump Search. For example:
Jump Search jumps ahead by √n steps, then performs linear search in the block where the element might be located.
Header Files Used
Understanding Jump Search
Algorithm Concept
:
Visual Example
:
Array: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
n = 16, step = √16 = 4
Jump 1: Check arr[3] = 2 < 55 → continue
Jump 2: Check arr[7] = 13 < 55 → continue
Jump 3: Check arr[11] = 89 > 55 → found block [8, 11]
Linear search in block: arr[8]=21, arr[9]=34, arr[10]=55 → found!
Function: jumpSearch()
int jumpSearch(int arr[], int n, int key) {
int step = sqrt(n);
int prev = 0;
while (arr[min(step, n) - 1] < key) {
prev = step;
step += sqrt(n);
if (prev >= n) {
return -1;
}
}
// Perform linear search in the block
while (arr[prev] < key) {
prev++;
if (prev == min(step, n)) {
return -1;
}
}
if (arr[prev] == key) {
return prev;
}
return -1;
}
1// Find the block where element might be
How it works
:
Step-by-Step Algorithm
Step 1: Calculate Step Size
Step 2: Find Block
Step 3: Linear Search in Block
Step 4: Return Result
Understanding Step Size
Why √n?
Example
(n = 16):
Time and Space Complexity
Time Complexity
: O(√n)
Space Complexity
: O(1)
When to Use Jump Search
Best For
:
Not Recommended For
:
Comparison with Other Search Algorithms
vs Linear Search
:
vs Binary Search
:
Important Considerations
Array Must Be Sorted
:
Step Size Calculation
:
Block Boundaries
:
return 0;
This ends the program successfully.