Listen To This Article

Listen to this post

Ready to play

 


public class BinarySearchExample {

    public static void main(String[] args) {

        // Example sorted array (could be user IDs)

        int[] sortedArray = {1, 5, 8, 12, 15, 19, 22, 26, 29, 35, 40, 45};

        int target = 15; // Target to find


        int index = binarySearch(sortedArray, target, 0, sortedArray.length - 1);

        if (index != -1) {

            System.out.println("Target found at index: " + index);

        } else {

            System.out.println("Target not found.");

        }

    }


    // Binary search method

    public static int binarySearch(int[] arr, int target, int left, int right) {

        while (left <= right) {

            int mid = left + (right - left) / 2;


            // Check if target is present at mid

            if (arr[mid] == target) {

                return mid;

            }


            // If target greater, ignore left half

            if (arr[mid] < target) {

                left = mid + 1;

            }

            // If target is smaller, ignore right half

            else {

                right = mid - 1;

            }

        }


        // Target was not found

        return -1;

    }

}


Comments

Sign Up For Our Free Newsletter & Vip List