Java Code for Binary Search using array example

                        Binary Search searches the specified value (key) in a sorted array (Ascending) and returns the position. Let us see how the Binary Search algorithm works. In this search algorithm, the key is compared with the middle element of the array. If it matches, then the key is found at the middle of the array. If the key is less than the middle element, then the key should be found at left side of the middle element. If the key is greater than the middle element, then the  key should be found at the right side of the middle element. The search continues on either lower half or upper half  of the array.

Consider an array (A) having n elements. Key is the value to be searched. low ->1, high-> n. Now find mid -> (low+high) /2. If Key==A[mid], then position -> mid, if Key<A[mid], then high->mid-1, if Key>A[mid], then low->mid+1, else not found

For Example let us take the numbers  77,33,22,55,34 and find the position of   55 in the list. Sorted list will be 22,33,34,55,77. Middle position is 3 and the  element is 34. Now 55 is compared with 34 and  55 is greater than 34. So the key will be on right side of 34. Now the search continues with elements 55 & 77, and the middle position is 4, now key 55 is compared with 55. Both are equal, so the key is found at 4th position.

In two ways, we can do binary search. One is using the Collections.binarySearch(List list, Object key)   OR We can write our own function as given below


package net.javaonline;

import java.util.Arrays;
import java.util.Scanner;

public class BinarySearch {
	public static void main(String[] args) {
		Scanner sc = new Scanner(;
		System.out.print("Enter howmany numbers are in in the array ");
		int n = sc.nextInt();
		int[] arr = new int[n];
		int key = 0;
		System.out.println("Enter " + n + " numbers");
		for (int i = 0; i < arr.length; i++) {
			arr[i] = sc.nextInt();
				.print("Enter any number to search in array using binary search ");
		key = sc.nextInt();
		System.out.print("Given List of  Numbers : ");
		for (int element : arr)
			System.out.print(element+ " ");
		System.out.print("List of Numbers after Sorting");
		for (int element : arr)
			System.out.print(element+ " ");
		System.out.println(" ");
		int pos = binsearch(key, arr);
		if (pos == -1)
			System.out.println("Given Number " + key + " Not Found");
			System.out.println("Given Number " + key + " Found at Position "
					+ (pos + 1));

	// Binary Search algorithm
	public static int binsearch(int searchValue, int[] searchList) {
		int high = searchList.length - 1;
		int low = 0;
		while (low <= high) {
			int mid = (low + high) / 2;
			if (searchValue > searchList[mid])
				low = mid + 1;
			else if (searchValue < searchList[mid])
				high = mid - 1;
				return mid;
		return -1;



binary search


Leave a Reply

best natural male enhancer python 4k male performance enhancement male enhancement otc sensual tabs male enhancement virmax natural male enhancement 8 hour power up pills extenze male enhancement walmart male enhancement pills from gas stations red hard male enhancement pill ron jeremy penis enhancement pills paradise male enhancement pills penis enlargement surgery in belgium enerex male enhancement blood flow increase supplements purplerhino male enhancement reviews male enhancement pills heb penis enlargement hypnosis male sexual enhancement pills australia bill maher penis enlargement natural penis enhancer trustworthy penis enlargement pills how to take hardcore male enhancement hardon pills penis enlargement routines drugs that boost libido sinus medicine erectile dysfunction long lasting pill safest pills to get high pill strength way to enlarge your penis nuibian sex pills marley ed pills how can i make my dick bigger without pills male girth enhancement near me after sex pills for guys toprevent infections pill that makes your penis bigger

cbd pods for juul thc vs cbd topicals cannabis cbd vs hemp cbd cannabis oil pain cbd and driving organabus cbd reviews is cbd oil legal in maryland cbd kratum cbd and afib cbd oil to treat neuropathy does cbd come up on a drug test cbd oil really work jolly green cbd source naturals cbd oil cbd oil science wild hemp brand cbd oil will insurance cover cbd oil cbd lawton ok cbd pills reviews cbd producers utah cbd registration cbd oil for torn ligaments wentworth hotel sydney cbd cbd black friday buy cbd isolate bulk lauras mercantile cbd oil time release cbd oil buy cbd distillate oil cbd dosage for humans cbd rosin avidekel cbd oil creating better days cbd review cbd oil italia cbd oil for autism amazon cbd oil effects fade health naturals cbd tincture 250mg

diabetic diet weight loss 7 day diet menu to lose weight loss weight fast diet plan quick weight loss center supplements alternatives keto fit diet pills canada celiac disease gluten free diet weight loss beef sausage keto diet recipes free tester weight loss pills how do i diet to lose weight post pregnancy weight loss diet plan sample diet menu to lose weight diet plan fot weight loss veg diet recipes to lose weight lipozene weight loss supplement diet pill best diet plan to lose weight fast for men best cookie diet weight loss weight loss shake diet plans the keto diet for weight loss vincent miles thermal pills for weight loss rapid weight loss plant based diet brith control pills for weight loss how to help a papillon lose weight can the doctor prescribe weight loss pills how fast will i lose weight on a ketogenic diet weight loss pills that dont cause anxiety reddit what rx drug has made you lose weight leap diet and weight loss vitamin supplements help weight loss vegetable only diet for weight loss raw vegan diet weight loss indian nutritionist diet plan for weight loss veg protein diet for weight loss pills to help me lose weight in stomach healthy diet no weight loss blue pills help you lose weight fast best diet for weight loss with thyroid problems