Binary search in java

problem

You have an array of numbers that are sorted in ascending order and you wish to apply the binary search algorithm using Java.

SOLUTION

Let’s implement the algorithm:

BinarySearch.java
				
					import java.util.Arrays;

public class BinarySearch {

    public static void main(String[] args) {

        int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10}; //pre-sorted in Ascending order, for binary search to work!

        boolean found = false; //let's set a flag that the number we're searching for is not found
        int searchNumber = 4; //a number to search for in our list

        //loop while the number is not found and our list of numbers has more than 2 elements
        while(!found && numbers.length >= 2){
            //search
            //get the middle item in the list
            int middleIndex = numbers.length / 2;
            System.out.println("checking middleIndex " + numbers[middleIndex] + " if equals to " + searchNumber);
            //check if it's the number you're looking for
            if (searchNumber == numbers[middleIndex]) {
                found = true;
                break; //exit the loop
            }//else...

            //half the array based on the number
            if(searchNumber > numbers[middleIndex]) {
                //keep the right part
                int[] newNumbers = Arrays.copyOfRange(numbers, middleIndex, numbers.length);
                System.out.println("halfing greater: " + Arrays.toString(newNumbers));
                numbers = newNumbers.clone(); // set it to our numbers array
            }else {
                //half the other side
                //keep the right part
                int[] newNumbers = Arrays.copyOfRange(numbers, 0, middleIndex);
                System.out.println("halfing less: " + Arrays.toString(newNumbers));
                numbers = newNumbers.clone(); // set it to our numbers array
            }
            //keep looping
        }

        //print if found or not
        if(found){
            System.out.println("Number " + searchNumber + " is found in the list.");
        }else {
            System.out.println("Number " + searchNumber + " is not found in the list!");
        }
    }
}
				
			
running

Let’s compile it in the terminal:

				
					javac BinarySearch.java 
				
			

Run the class file

				
					java BinarySearch
				
			
output
Binary Search output for number 4 - in Java

This algorithm keeps making the array of numbers smaller and smaller until it’s found the number. If not, the array ends up having only 2 or less elements and the loop stops, meaning that it’s not found.

conclusion

In this post we saw how to implement the Binary Search algorithm and execute it, little bit different approach than the pseudocode that is found online. 

References:

https://en.wikipedia.org/wiki/Binary_search

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies (Ads)

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings. We use Google Ads on this site.

Google Analytics Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.

HotJar Cookies

We use Hotjar in order to better understand our users’ needs and to optimize this service and experience. Hotjar is a technology service that helps us better understand our users’ experience (e.g. how much time they spend on which pages, which links they choose to click, what users do and don’t like, etc.) and this enables us to build and maintain our service with user feedback. Hotjar uses cookies and other technologies to collect data on our users’ behavior and their devices. This includes a device's IP address (processed during your session and stored in a de-identified form), device screen size, device type (unique device identifiers), browser information, geographic location (country only), and the preferred language used to display our website. Hotjar stores this information on our behalf in a pseudonymized user profile. Hotjar is contractually forbidden to sell any of the data collected on our behalf.

For further details, please see the ‘about Hotjar’ section of Hotjar’s support site.