Binary search algorithm


Binary search algorithm

 wikipedia :https://en.wikipedia.org/wiki/Binary_search_algorithm








public 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 

Popular posts from this blog

youtube download

com.gpki.secureweb.GPKISecureWEBException: ErrCode=1507,ErrMsg=[GPKI_CMS_ProcessEnvelopedData] 해당 인증서로는 데이터를 풀 수 없습니다.

rexpert 공식필드(javascript) 점검일 주기 계산