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.

Code:

</pre>
public class BinarySearch1
{
 public static void main(String[] args)
 {
 Scanner keyboard = new Scanner(System.in);
 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);
 }//for

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

System.out.println();

//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[bottom..top]
 do
 {
 middle = (top + bottom) /2;
 if(myArray[middle] == searchValue)
 {
 found = true;
 location = middle;
 }//if

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

else
 {
 top = middle - 1;
 }//else

finished = found || (top < bottom);

}//do
 while (!finished);

if(!found)
 {
 System.out.println("Number not found.");
 }//if

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

}//main
}//class
<pre>

 

One thought on “Binary Search – Java program

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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