* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package serch;
/**
*
* @author KAPILAN
*/
public class BSearch {
int [] array={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
int n;
int key;
public BSearch(){
//this.key=key;
// array={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
n=array.length;
}
public int serch(int key){
return serch(key,0,n-1);
}
public int serch(int key,int s, int e) {
int mid=(s+e)/2;
if(e<s){return -1;}
else if(key==array[mid]){return mid;}
else if(key<array[mid]){return serch(key,s,mid-1);}
else{return serch(key,mid+1,e);}
}
public void print(int key){
System.out.println("index of "+key+" = "+serch(key));
}
public static void main(String[] a){
BSearch s1=new BSearch();
s1.print(20);
}
}
/*
index of 10 = 9
* index of 22 = -1
* index of 2 = 1
* index of 0 = -1
* index of 20 = 19
*/
No comments:
Post a Comment