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
48 changes: 48 additions & 0 deletions Jump Search
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
//Jump Search is a searching algorithm for sorted arrays
//suppose we have an array arr[] of size n and a block (to be jumped) of size m.
//Then we search in the indexes arr[0], arr[m], arr[2m]…..arr[km] and so on.
//Once we find the interval (arr[km] < x < arr[(k+1)m]),
//we perform a linear search operation from the index km to find the element x
#include <bits/stdc++.h>
using namespace std;

int jumpSearch(int arr[], int x, int n)
{
int step = sqrt(n);
int prev = 0;
while (arr[min(step, n)-1] < x)
{
prev = step;
step += sqrt(n);
if (prev >= n)
return -1;
}

while (arr[prev] < x)
{
prev++;

if (prev == min(step, n))
return -1;
}

if (arr[prev] == x)
return prev;

return -1;
}


int main()
{
int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21,
34, 55, 89, 144, 233, 377, 610 };
int x = 55;
int n = sizeof(arr) / sizeof(arr[0]);


int index = jumpSearch(arr, x, n);

cout << "\nNumber " << x << " is at index " << index;
return 0;
}