Sabtu, 06 September 2025

JAVA - Binary Search with Array

 





/*

 * To change this license header, choose License Headers in Project Properties.

 * To change this template file, choose Tools | Templates

 * and open the template in the editor.

 */

package binarysearcharray;

public class BinarySearchArray {


    /**

     * Performs a binary search on a sorted array to find the index of a target element.

     *

     * @param arr    The sorted array to search within.

     * @param target The element to search for.

     * @return The index of the target element if found, otherwise -1.

     */

    public static int binarySearchArray(int[] arr, int target) {

        int left = 0;

        int right = arr.length - 1;


        while (left <= right) {

            // Calculate the middle index to avoid potential overflow with (left + right) / 2

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


            if (arr[mid] == target) {

                return mid; // Target found at index mid

            } else if (arr[mid] < target) {

                left = mid + 1; // Target is in the right half, so adjust 'left'

            } else {

                right = mid - 1; // Target is in the left half, so adjust 'right'

            }

        }


        return -1; // Target not found in the array

    }


    public static void main(String[] args) {

        int[] sortedArray = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};

        int target1 = 9;

        int target2 = 4;


        int result1 = binarySearchArray(sortedArray, target1);

        if (result1 != -1) {

            System.out.println("Element " + target1 + " found at index: " + result1);

        } else {

            System.out.println("Element " + target1 + " not found.");

        }


        int result2 = binarySearchArray(sortedArray, target2);

        if (result2 != -1) {

            System.out.println("Element " + target2 + " found at index: " + result2);

        } else {

            System.out.println("Element " + target2 + " not found.");

        }

    }

}


Tidak ada komentar: