binary-search-array-java

Binary Search Array Java

This is one the favorite interview questions in any Java interview if they give programming exercise:

import java.util.Arrays;
import java.util.Collections;

public class SearchInBinaryTree {

	public static void main(String[] args) {

		int number = 1;

		Integer input[] = { 1, 56, 32, 48, 2, 25, 69, 23, 1, 4, 5, 79 };
		Arrays.sort(input);
		if (binarySearchInArray(input, number) != -1) {
			System.out.println("Number found in array and its index position is: -->"+binarySearchInArray(input, number));	
		}else{
			System.out.println("Number not ound in array");
		}
		

	}

	public static Integer binarySearchInArray(Integer[] input, Integer number) {
		
		Integer low = 0;
		Integer high = input.length - 1;
		
		while (high >= low) {
			Integer middle = (low + high) / 2;
			if (input[middle] == number) {
				return middle;
			} else if (input[middle] < number) {
				low = middle + 1;
			} else if (input[middle] > number) {
				high = middle - 1;
			}
		}
		return -1;
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *