Binary search algorithm
Binary search algorithm
wikipedia :https://en.wikipedia.org/wiki/Binary_search_algorithmpublic class binarySearch {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int[] quest = {1,5,6,9,12,17,20,29,38,60,61,68,81,90,95,99};
for( int i : quest){
System.out.print(i+" ");
}
System.out.print("\nkey? : ");
int answer = in.nextInt();
System.out.print("result : "+search(quest, answer,0, quest.length)+" ");
}
public static int search(int[] quest, int key, int min, int max){
if(min > max) return -1;
int mid = (min +max)/2;
if(key==quest[mid])
return mid+1;
else if(key>quest[mid])
return search(quest, key, mid+1,max);
else if(key<quest[mid])
return search(quest, key, min, mid-1);
else
return -1;
}
}//class
-----------------------------------------------------------------------------------------------
result :
1 5 6 9 12 17 20 29 38 60 61 68 81 90 95 99
key? : 61
result : 11