Algorithm Deep Dive Java Implementation

Implementation of Binary Search Algorithm in Java

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:

Iterative Implementation of Binary Search in Java

Let’s start with the iterative implementation of the binary search algorithm in Java:

Loading code…

Explanation

  1. Initialization: We start with low at the beginning of the array and high at the end.
  2. Loop: The search continues as long as low is less than or equal to high.
  3. Middle Element: We calculate mid and compare arr[mid] with the target.
  4. Update Pointers: Based on the comparison, we adjust low or high.
  5. 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:

Loading code…

Explanation

  1. Base Case: If low exceeds high, the target is not in the array.
  2. Middle Element: We calculate mid and compare arr[mid] with the target.
  3. 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.
  4. Return: If the target is found, we return its index. Otherwise, we propagate the -1 from 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:

  1. When arr[mid] < target, we now search the left half (instead of right).
  2. 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.