How to use binary search in Java to find arrays with the same elements?

In order to use Java to perform a binary search for elements with the same value in an array, it is essential to ensure that the array is already sorted in either ascending or descending order. Following that, you can implement the binary search by utilizing the following code:

public class BinarySearch {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 3, 4, 5, 6};
        int target = 3;
        
        int left = binarySearchLeft(nums, target);
        int right = binarySearchRight(nums, target);
        
        if (left == -1 || right == -1) {
            System.out.println("No elements found.");
        } else {
            for (int i = left; i <= right; i++) {
                System.out.println("Element found at index: " + i);
            }
        }
    }
    
    public static int binarySearchLeft(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int index = -1;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            
            if (nums[mid] == target) {
                index = mid;
                right = mid - 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        
        return index;
    }
    
    public static int binarySearchRight(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int index = -1;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            
            if (nums[mid] == target) {
                index = mid;
                left = mid + 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        
        return index;
    }
}

In this example, we defined two helper functions, binarySearchLeft and binarySearchRight, to find the left and right boundaries of elements in the array that are the same.Then we called these two functions in the main method and printed the indices of all elements that meet the condition.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds