Binary search program in Java

Binary search is the step in searching techniques. Because of the draw backs of linear search, binary search came into light. The major difference between Linear and Binary search is, in linear search we need not to sort the given array. But for binary search to be done, we need to sort the array either in ascending or descending order.

Procedure for binary search:

1. Get the input array from the user.
2. Sort the array either in ascending or descending order.
3. Now, for searching, first compare the middle term of the array with the search element.
4. If the element matches the middle term, display output.
5. If the middle term doesn’t match and if middle term is greater than searching element, then from next iteration consider only the first half of the array.
6. If the middle term is lesser, then consider second half of the given array.
7. After considering the half of the array, goto step 3.

import java.util.*;
import java.io.*;

public class binarysearch{
	public static void main(String args[]){
		
		int temp, first, last, middle,i;
		Scanner in = new Scanner(System.in);
		System.out.println("Enter size of the integer array:");
		int size = in.nextInt();
		int[] data = new int[size];
		for(i=0; i<size; i++){
			System.out.println("Enter next element of the array:");
			data[i] = in.nextInt();
		}
		
                //bubble sort in ascending order
		for(i=0; i<size; i++) {
			for(int j=0; j<i; j++){
				if(data[i] < data[j]){
					temp = data[j];
					data[j] = data[i];
					data[i] = temp;
				}
			}			
		}

		System.out.println("\nEnter the element to be searched:");
		int key = in.nextInt();
		first = 0;
		last = size-1;
		while(first <= last){
			middle = (first+last)/2;
			if(data[middle] == key){
				System.out.println("Key element found");
				break;
			}
			else if(data[middle] > key)
				last = middle-1;
			else if(data[middle] < key)
				first = middle+1;
		}
		if(first > last)
			System.out.println("Element not found");
	}
}

Output:
binarysearch

Download the source code

Advertisement
This entry was posted in Java and tagged , , , , , , . Bookmark the permalink.

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 )

Facebook photo

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

Connecting to %s