Tuesday, April 12, 2016

Binary Search Example in java

import java.util.Scanner;

public class BinarySearch {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
//initialize an array of type int that stores the value of prime no.
int [] prime = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97};
int max = prime.length;
int min = 0;
int count=0;
System.out.println("Enter the target no (0,100) make sure the no is prime.");
int target = input.nextInt();
input.close();
int guess = (max+min)/2;
while(target!=prime[guess]){
  if(prime[guess]>target){
  max = guess;
  guess = (max+min)/2;
 
  }
  else{
  min=guess
  guess = (max+min)/2;
 
}
  count++;
}
if(target==prime[guess])System.out.println("The prime no is :"+prime[guess]+" and the position is :"+guess);
System.out.println("no of guesses :"+count);
}


}

No comments: