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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay