In the world of computer programming, binary search is one of the most important sorting algorithms. The core concept behind this is the principle of divide and concate technique. In this tutorial, we are going to implement a binary search algorithm in Java language.
Table of Contents
How Binary Search Works
Following are the steps used in the binary search algorithm
- Set LEFT and RIGHT to the begining and end of the sorted array(we can apply binary search only on sorted Array)
- Calculate Middle Index Mid = LEFT + (RIGHT – LEFT) /2
- If Array[mid] = target, element is found and break the loop
- If Array[mid] < target, update LEFT = mid +1, start with step 1
- Elseif array[mid] > target update RIGHT = mid -1, start with step 1
- Continue step 1 to 5 until the target is found or LEFT becomes greater than the RIGHT
Binary Search Java Code
public class BinarySearchDemo {
public static int binarySearch (int array[], int target) {
int LEFT = 0;
int RIGHT = array.length - 1;
while (LEFT <= RIGHT) {
int mid = LEFT + (RIGHT - LEFT) / 2;
// If mid value = target
if (array[mid] == target) {
return mid;
}
if (array[mid] < target) {
LEFT = mid + 1;
} else {
RIGHT = mid - 1;
}
}
return -1;
}
public static void main(String[] args) {
int [] array = { 2, 4, 6 ,7, 34, 43,56,65,67,76,78,87};
int target = 34;
int index = binarySearch(array,target);
if(index == -1){
System.out.println("Target value not found in the Array");
}
else {
System.out.println("Target value found in the array at index " + index);
}
}}
1 thought on “Binary Search Algorithm : Java Implementation”