Binary Search – Java program

What it does:

A simple Java program which initials an array though a loop giving it the multiples of two. It then gives a print out of the array and lets the user search for a number where it would return if it is found or not.


public class BinarySearch1
 public static void main(String[] args)
 Scanner keyboard = new Scanner(;
 final int SIZE = 10;
 int myArray [] = new int[SIZE];
 boolean found, finished;
 int top, middle, bottom, searchValue;

//loading up array using a multiple of count
 for(int count = 0; count <SIZE; count++)
 myArray [count] = (count*2);

//printing array
 System.out.println("Array initialised: ");
 for(int count =0; count < SIZE; count++)
 System.out.print(myArray[count] + " ");


//Now enter a search value
 System.out.println("Now, enter a number to look for: ");
 searchValue = keyboard.nextInt();

//preset necessary control variables
 int location = 0;
 found = false;
 top = SIZE-1;
 bottom = 0;

//at any stage if search value is in the array it is in the section myArray[]
 middle = (top + bottom) /2;
 if(myArray[middle] == searchValue)
 found = true;
 location = middle;

else if(myArray[middle] < searchValue)
 bottom = middle + 1;

 top = middle - 1;

finished = found || (top < bottom);

 while (!finished);

 System.out.println("Number not found.");

 System.out.println("Number found successfully at index position "+ location);



One thought on “Binary Search – Java program

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s