java-이분 찾기

2 분 검색 도 절반 검색 이 라 고 하 는데 전 제 는 배열 이 질서 있 는 배열 이 고 다음은 원 리 를 분석 하 는 것 이다.
만약 배열 이 있다 면:
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;
    }
}

좋은 웹페이지 즐겨찾기