search algorithm using sentinel

Posted by davit-datuashvili on Stack Overflow See other posts from Stack Overflow or by davit-datuashvili
Published on 2010-05-29T09:01:22Z Indexed on 2010/05/29 9:02 UTC
Read the original article Hit count: 237

Filed under:

i am trying to do search algorithm using sentinel which reduce time to 3.87n nanoseconds for example compare to this code

 int search (int t ){



      for (int i=0;i<n;i++)
  if (x[i]==t)
   return i;
  return -1;

}

it takes 4.06 nanoseconds

so i am trying to optimize it here is code

public class Search{

public static int search(int a[],int t){
int i;
int p=0;
 int n=a.length;
int hold;
 hold=a[n-1];
 a[n-1]=t;
  for ( i=0;;i++)
  if (a[i]==t)  break;
    a[n-1]=t;
  if (i==n){
 p= -1;
}

else{

p= i;
}


return p;
}
public static  void main(String[]args){
int t=-1;
int a[]=new int[]{4,5,2,6,8,7,9};
 System.out.println(search(a,t));









}
}

but is show me that 9 is at position 6 which is correct but if t =1 or something else which is not array it show me position 6 too please help

© Stack Overflow or respective owner

Related posts about algorithm