Let's begin!
It's a Searching Algorithm with average time complexity as root n.
Instead of going one by one through elements (like linear search), it jumps from element to element in a sorted array. The jump value is root of the length of array.
If target element is found return true.
Else If current element is less than target and within the range call the function with change parameters.
Else If current element is greater than target and within the range call the function with change parameters.
Else return false.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <math.h> | |
bool JumpSearch(int *arr, int jump, int target, int length, int initial = 0) | |
{ | |
if (arr[initial] == target) | |
{ | |
return true; | |
} | |
else if (arr[initial] < target and arr[length-1] >= target) | |
{ | |
initial += jump; | |
return JumpSearch(arr, jump, target, length, initial); | |
} | |
else if (arr[initial] > target and arr[0] <= target) | |
{ | |
return JumpSearch(arr, jump, target, length, --initial); | |
} | |
else | |
{ | |
return false; | |
} | |
} | |
int main() | |
{ | |
int arr[] = {1,2,3,4,5,6,7}; | |
int length = 7; //length of array | |
int target = 4; //element to be found | |
int jump = sqrt(length); //jump to be taken : IDEAL root of the arrary's length | |
std::cout<<JumpSearch(arr, jump, target, length); | |
return 0; | |
} |
Comments
Post a Comment