jdk 7 에서 sort 내부 알고리즘 변경

2965 단어 sort
jdk 7 에서 sort 의 알고리즘 이 바 뀌 었 습 니 다.
Arrays. sort 를 예 로 들 면:

public static <T> void sort(T[] a, Comparator<? super T> c) {
        if (LegacyMergeSort.userRequested)
            legacyMergeSort(a, c);
        else
            TimSort.sort(a, c);
    }
LegacyMergeSort.userRequested       
    	 Boolean b = java.security.AccessController.doPrivileged(
                 new sun.security.action.GetBooleanAction("java.util.Arrays.useLegacyMergeSort")).booleanValue();
    	 System.out.println(b);

기본 값 은 false, 즉 기본 값 은 timsort 알고리즘 입 니 다.Legacy MergeSort 는 간단하게 배열 을 2 분 의 2 로 나 누 어 그룹 을 나 눈 다음 각 그룹 은 정렬 알고리즘 을 삽입 하여 각 그룹 을 처리 한 다음 정렬 합 니 다.

    /**
     * Old merge sort implementation can be selected (for
     * compatibility with broken comparators) using a system property.
     * Cannot be a static boolean in the enclosing class due to
     * circular dependencies. To be removed in a future release.
     */
    static final class LegacyMergeSort {
        private static final boolean userRequested =
            java.security.AccessController.doPrivileged(
                new sun.security.action.GetBooleanAction(
                    "java.util.Arrays.useLegacyMergeSort")).booleanValue();
    }

주의:
Cannot be a static boolean in the enclosing class due to circular dependencies. To be removed in a future release.
timsort 의 일부 변 화 는:
1. 재 귀 등 수량 을 사용 하지 않 고 2 분 으로 나 누 기
2. 내부 각 그룹 은 2 점 삽입 정렬 을 사용 합 니 다.
3. 누구 와 누구 에 게 규칙 이 있 습 니까?
인터넷 의 일부 네티즌 들 은 이전 버 전의 코드 가 jdk 7 에서 이상 하 게 던 진 것 을 발견 했다.

public class ReproJava7Exception {
    public static void main(String[] args) {
        int[] sample = new int[]
              {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
                0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-2,1,0,-2,0,0,0,0};
        List<Integer> list = new ArrayList<Integer>();
        for (int i : sample)
            list.add(i);
        // use the native TimSort in JDK 7
        Collections.sort(list, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                // miss the o1 = o2 case on purpose
                return o1 > o2 ? 1 : -1;
            }
        });
    }
}

해결 방법 은 Comparable 인 터 페 이 스 를 실현 할 때 1, 1, 0 을 모두 나 누 어야 한다.
참조:
http://www.lifebackup.cn/timsort-java7.html
http://en.wikipedia.org/wiki/Timsort

좋은 웹페이지 즐겨찾기