In the previous article, we explored the binary search algorithm and wrote pseudocode for both iterative and recursive approaches. Now, it’s time to bring that pseudocode to life by implementing binary search in Java. By the end of this article, you’ll have a working implementation of binary search and a clear understanding of how to use it in your programs.
Prerequisites:
- Introduction to binary search for beginners
- Binary Search Algorithm: Step-by-Step Explanation and Visualization
- Binary Search Algorithm: Pseudocode and Explanation
Iterative Implementation of Binary Search in Java
Let’s start with the iterative implementation of the binary search algorithm in Java:
Explanation
- Initialization: We start with
lowat the beginning of the array andhighat the end. - Loop: The search continues as long as
lowis less than or equal tohigh. - Middle Element: We calculate
midand comparearr[mid]with the target. - Update Pointers: Based on the comparison, we adjust
loworhigh. - Return: If the target is found, we return its index. Otherwise, we return
-1.
Example Usage
public class BinarySearchExample {
public static void main(String[] args) {
// Create a sorted array
int[] arr = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
// Define the target value we're searching for
int target = 23;
// Perform the binary search
int result = BinarySearch.binarySearchIterative(arr, target);
// Check and display the result
if (result != -1) {
System.out.println("Target found at index " + result + ".");
} else {
System.out.println("Target not found.");
}
}
}
Output:
Target found at index 5.
Recursive Implementation of Binary Search in Java
Now, let’s look at the recursive implementation of the binary search algorithm in Java:
Explanation
- Base Case: If
lowexceedshigh, the target is not in the array. - Middle Element: We calculate
midand comparearr[mid]with the target. - Recursive Calls:
- If the target is greater than
arr[mid], we search the right half of the current search space. - If the target is less than
arr[mid], we search the left half of the current search space.
- If the target is greater than
- Return: If the target is found, we return its index. Otherwise, we propagate the
-1from the base case.
Example Usage
public class BinarySearchExample {
public static void main(String[] args) {
int[] arr = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
int target = 23;
int result = BinarySearch.binarySearch(arr, target);
if (result != -1) {
System.out.println("Target found at index " + result + ".");
} else {
System.out.println("Target not found.");
}
}
}
Output:
Target found at index 5.
Binary Search for Descending Order Lists
So far, we’ve implemented binary search for arrays sorted in ascending order. But what if our array is sorted in descending order? Let’s explore the changes we need to make to our binary search implementations to handle this case.
Changes in the Algorithm
The core logic of binary search remains the same, but we need to adjust our comparisons:
- When
arr[mid] < target, we now search the left half (instead of right). - When
arr[mid] > target, we now search the right half (instead of left).
Iterative Implementation for Descending Order
Here’s how we can modify our iterative implementation for descending order arrays:
public static int binarySearchIterativeDesc(int[] arr, int target) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
high = mid - 1; // Search left half
} else {
low = mid + 1; // Search right half
}
}
return -1;
}
Recursive Implementation for Descending Order
Similarly, we can adjust our recursive implementation:
public static int binarySearchRecursiveDesc(int[] arr, int target, int low, int high) {
if (low > high) {
return -1;
}
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
return binarySearchRecursiveDesc(arr, target, low, mid - 1);
} else {
return binarySearchRecursiveDesc(arr, target, mid + 1, high);
}
}
Example Usage
public class BinarySearchDescExample {
public static void main(String[] args) {
int[] arrDesc = {91, 72, 56, 38, 23, 16, 12, 8, 5, 2};
int target = 23;
int result = binarySearchIterativeDesc(arrDesc, target);
if (result != -1) {
System.out.println("Target found at index " + result + ".");
} else {
System.out.println("Target not found.");
}
}
}
Output:
Target found at index 4.