java-이분 찾기
만약 배열 이 있다 면:
int arr[] = {1,2,3,4,5,6};
1 이 있 는 색인 값 을 찾 으 려 면 최대 색인 값 maxIndex 와 최소 색인 값 minIndex 를 확인 한 다음 중간 색인 값 과 midIndex 를 계산 합 니 다.
int maxIndex = arr.length-1;
int minIndex = 0;
int midIndex = (minIndex + maxIndex)/2;
중간 색인 값 에 따라 중간 요소 와 1 을 찾 습 니 다.다음 과 같이 midValue 와 1 의 값 을 비교 합 니 다.midValue 가 1 보다 크 면 배열 arr[minIndex]에서 arr[midIndex-1]에서 위의 비교 결 과 를 계속 하고 진행 합 니 다.midValue 가 1 보다 작 으 면 여러 그룹 arr[minIndex+1]에서 arr[maxIndex]에서 위의 비 교 를 계속 합 니 다.찾 으 면...색인 을 되 돌려 줍 니 다.minIndex>maxIndex 가 끝 날 때 까지 찾 지 못 하면 되 돌아 오지 못 했 음 을 의미 합 니 다.-1.
while (arr[midIndex] != value) {
if (arr[midIndex] > value) {
maxIndex = midIndex - 1;
} else {
minIndex = midIndex + 1;
}
if (minIndex > maxIndex) {
return -1;
}
midIndex = (minIndex + maxIndex) / 2;
}
return midIndex;
하면,만약,만약...
예.
2 분 검색 시간 복잡 도:log2n 참조:http://blog.csdn.net/frances_han/article/details/6458067
전체 코드:
public class BinarySearch {
public static void main(String[] args) throws Exception {
int arr[] = {1, 2, 3, 4, 5, 6};
int index = getIndex(arr, 1);
System.out.println("index:" + index);
int index = getIndex(arr, 7);
System.out.println("index:" + index);
}
private static int getIndex(int[] arr, int value) {
int minIndex = 0;
int maxIndex = arr.length - 1;
int midIndex = (minIndex + maxIndex) / 2;
while (arr[midIndex] != value) {
if (arr[midIndex] > value) {
maxIndex = midIndex - 1;
} else {
minIndex = midIndex + 1;
}
if (minIndex > maxIndex) {
return -1;
}
midIndex = (minIndex + maxIndex) / 2;
}
return midIndex;
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
귀속할 필요가 없는 2점 찾기오늘 동료가 차에서 나에게 면접을 본다고 했는데, 이 문제가 있었는데, 그는 해내지 못했다 회사에 가서 직접 간단히 썼다....
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.