Skip to content

Added Jump Search #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
46 changes: 46 additions & 0 deletions Searching/c++/jump-search.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#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 n,i;
cout<<"Eneter size of array : ";
cin>>n;
cout<<"Enter elements of array"<<endl;
int a[n];
for(i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
cout<<"Enter key to be searched : ";
int key;
cin>>key;
int index = jumpSearch(a, key, n);
cout << "\nNumber " << key << " is at index " << index;
return 0;
}