jump search algorithm
i am doing jump search algorithm but it show me that element is not in array while it is here is code
import java.math.*;
public class jamp {
public static int min(int a,int b) {
return a<b?a:b;
}
public static void main(String[]args) {
开发者_Python百科 int a[]=new int[]{3,7,9,12,14,15,16,17,18};
int l=14;
System.out.println(jumpsearch(a,a.length,l));
}
public static int jumpsearch(int a[],int n, int l ) {
int t=0;
int b=(int)Math.sqrt(n);
while (a[min(b,n)-1]<t){
t=b;
b=b+(int)Math.sqrt(n);
if ( t>=n) return -1 ;
}
while (a[t]<l){
t=t+1;
if ( t==min(b,n))
return -1 ;
if ( a[t]==l) {
return t;
}
}
return -1;
}
}
please help
Change
while (a[min(b,n)-1]<t){
to
while (a[min(b,n)-1]<l){ // t should be l
According to this article that value should be the search key. When I run the program with this change I get 4.
Here is my sample Example for Jump Search(Alternative Approach):- Hope this helps
public class JumpSearch {
public static void main(String[] args) {
int[] arr= {0,1,2,3,4,5,5,9,12,14,15,15};
System.out.println("Element found at: "+search(arr,15));
}
public static int search (int[] arr,int key){
int length= arr.length;
int start=0;
int jump=(int) Math.sqrt(length);
for(int i=0;i<length;i+=jump){
if(arr[i]==key){
return i;
}
else if(arr[i]>key){
start=arr[i-jump];
break;
}else{
start=i+1;
}
}
for(int i=start;i<arr.length;i++){
if(arr[i]==key){
return i;
}
}
return -1;
}
}
function jumpSearch($arr,$length,$searched_value){
$step=sqrt($length);
for($i=0;$arr[$i]<=$searched_value;$i=$i+$step){
if($arr[$i]==$searched_value){
return $i;
}else{
$last_up=$i;
}
}
$s=$last_up+1;
$l=$s+$step;
for($i=0;$i<=$l;$i++){
if($arr[$i]==$searched_value){
return $i;
}
}
}
$arr=array(0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610);
$length=count($arr);
$searched_value=34;
$result=jumpSearch($arr,$length,$searched_value);
if($result==-1){
}else{
echo "Search Found at ".$result;
}
精彩评论