습관제작소

22-05-23 JAVA Sort_Binery 본문

Programing Language/JAVA STUDY

22-05-23 JAVA Sort_Binery

KUDO 2022. 5. 23. 19:45

import java.util.Scanner;

public class Binery {

    public static void main(String[] args) {

        // Binery Search(이진 탐색)

        int[] arr = {1, 7, 8, 11, 27, 77, 96, 100, };

        Scanner sc = new Scanner(System.in);
        System.out.print("탐색할 값을 입력하세요 >> ");
        int search = sc.nextInt();

        int lowIndex = 0;
        int highIndex = arr.length-1;
        int midIndex = (lowIndex+highIndex) / 2;


        //내가 설정한 중간 인덱스의 값과 찾고자 하는 값이 같으면 while문 종료
        while(arr[midIndex]!=search) {

            if(arr[midIndex] < search) {
                lowIndex = midIndex+1;
            }
            else if(arr[midIndex]>search) {
                highIndex = midIndex-1;
            }
            if(lowIndex>highIndex) {
                midIndex=-1;
                break;
            }
            midIndex = (highIndex+lowIndex)/2;


        }
        System.out.println("내가 찾는 값은 index : "+ midIndex+"에 있다.");

    }

}
Comments