Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

이분 탐색 코드 #142

Closed
woochul2 opened this issue Apr 11, 2022 · 1 comment
Closed

이분 탐색 코드 #142

woochul2 opened this issue Apr 11, 2022 · 1 comment
Labels
good first issue Good for newcomers

Comments

@woochul2
Copy link

woochul2 commented Apr 11, 2022

안녕하세요, 자료가 정말 잘 정리돼있어서 공부에 잘 사용하고 있습니다. 감사합니다! 하나 궁금한 점이 있어 질문 남깁니다.

이분 탐색 코드를 보다가 sum은 왜 쓰였을까, end 변수는 왜 arr.length-1가 아닌 arr[arr.length-1]로 쓰였을까 같은 의문이 들었고, 코드가 잘 이해가 안 돼서 예시로 올려주신 코드를 그대로 복사하여 실행해봤습니다.

아래 코드를 실행했을 때 결과는 0이 나왔습니다.

int[] arr = {1,2,3,4,5,6};
int result = solution(arr, 5);
System.out.println(result);

repl 주소: https://replit.com/@woochul2/tech-interview-for-developer-binary-search#Main.java

결과로 원소 5의 인덱스인 4가 결과로 나와야할 것 같은데, 혹시 예시 코드에 오류가 있는 걸까요?

제가 알고리즘 초보이기도 하고, 자바를 잘 몰라서 잘못된 예시로 코드를 사용했을 수도 있을 것 같습니다. 혼자서는 의문이 해결되지 않아 질문 남깁니다.

@gyoogle gyoogle added the good first issue Good for newcomers label Apr 19, 2022
@gyoogle
Copy link
Owner

gyoogle commented Apr 19, 2022

안녕하세요. 해당 코드가 조금 문제도 있는 것 같고, 이분 탐색으로 학습하기에 적절한 코드가 아닌 것 같아 좀 더 쉬운 코드로 수정하겠습니다. 감사합니다:)

public static int solution(int[] arr, int M) { // arr 배열에서 M을 찾자
	
    Arrays.sort(arr); // 정렬
	
    int start = 0;
    int end = arr.length - 1;
    int mid = 0;

    while (start <= end) {
        mid = (start + end) / 2;
        if (M == arr[mid]) {
            return mid;
        }else if (arr[mid] < M) {
            start = mid + 1;
        }else if (M < arr[mid]) {
            end = mid - 1;
        }
    }
    throw new NoSuchElementException("타겟 존재하지 않음");
}

@gyoogle gyoogle closed this as completed Apr 19, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
good first issue Good for newcomers
Projects
None yet
Development

No branches or pull requests

2 participants