DEV Community

Mustafa  Çam
Mustafa Çam

Posted on

BinarySearch

import java.util.Arrays;

public class binarySearch {

    public static int BinarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;

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

            // Orta elemanı kontrol et
            if (arr[mid] == target) {
                return mid;
            }

            // Orta eleman hedeften küçükse sağ yarıya bak
            if (arr[mid] < target) {
                left = mid + 1;
            } 
            // Orta eleman hedeften büyükse sol yarıya bak
            else {
                right = mid - 1;
            }
        }

        // Hedef bulunamadıysa -1 döndür
        return -1;
    }

    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
        int target = 5;
        int result = BinarySearch(array, target);
        System.out.println("Index of " + target + ": " + result);
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)