Write a Java Program to Perform Binary Search in a Sorted Array

Write a Java Program to Perform Binary Search in a Sorted Array thumbnail
4K
By Dhiraj Ray 10 January, 2018

Description

Binary search is one of the famous and fundamental algorithm in computer science which solves a large number of problems in developing applications and APIs. It uses divide and conquer approach to find out the element.Here, we will be writing a sample program in java that implements binary search.The given array is a sorted array of n elements and we have to search the position a given element inside the array.

SampleBinarySearch .java
public class SampleBinarySearch {

	public int binarySearch(int[] arr, int key) {

		int start = 0;
		int end = arr.length - 1;
		while (start <= end) {
			int mid = (start + end) / 2;
			if (key == arr[mid]) {
				return mid;
			}
			if (key < arr[mid]) {
				end = mid - 1;
			} else {
				start = mid + 1;
			}
		}
		return -1;
	}

	public static void main(String[] args) {

		SampleBinarySearch sbs = new SampleBinarySearch();
		int[] arr = { 2, 4, 6, 8, 10, 12, 14, 16 };
		System.out.println("Key 14's position: " + sbs.binarySearch(arr, 14));
		int[] arr1 = { 6, 34, 78, 123, 430, 900 };
		System.out.println("Key 430's position: " + sbs.binarySearch(arr1, 430));
	}
 }

Worst case performance: O(log n)

Best case performance: O(1)

Explanation

Get the mid element from the array. As the array is sorted By comparing our input number with mid value we can break the array into two halves repeatedly and get the index of our input number.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.