Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 34: Write a Java program to perform binary search.

Binary.java

import java.util.Scanner;

//Class Binary search contains the method to perform binary search.
//Binary search works only on sorted array.

class BinarySearch
{
	//Method to perform binary search
	public static int binarySearch(int[] arr, int num)
	{
		int start=0;
		int end=arr.length-1;
		int temp=-1;
		while(start < end)
		{
			int mid=(start+end)/2;
			if(num==arr[mid])
			{
				temp=mid;
				break;
			}
			else if(num < arr[mid])
			{
				end=mid-1;
			}
			else
			{
				start=mid+1;
			}
		}
		return temp;
    }
}

//Main class
public class Binary
{
	static Scanner s1 = new Scanner(System.in);

	//Method to take input.
	public static int[] takeInput()
	{
		System.out.println("Enter the number of elements to be included in the array.");
		int size = s1.nextInt();
		int arr[] = new int[size];	
		System.out.println("Enter the element in the array");

		for (int i = 0; i < size; i++)
		{
			arr[i] = s1.nextInt();
		}
		return arr;
	}

	//Main method.
	public static void main(String[] args)
	{
		int[] arr = takeInput();
		System.out.print("Enter the element to be searched in the array");
		int num = s1.nextInt();

		if(num==-1)
		{
			System.out.println("Element not found");
		}
		else{
			System.out.print("Element "+num+" found at index ");
			System.out.print(BinarySearch.binarySearch(arr, num));
		}
	}
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.