tags:

views:

63

answers:

1

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) {
        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

+1  A: 

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.

Alex Winston
thanks thanks very much