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
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:
Share it!
Facebook
Twitter
LinkedIn
Reddit
Ellion
Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪
Tagged algorithms, data structures, sorting