search

Home  >  Q&A  >  body text

java - JDK7中Arrays工具类sort()对基本类型和对象采用不同排序算法的原因是什么?

如题,JDK7中的java.util.Arrays工具类中的排序方法sort()对基本类型和对象采用不同的排序算法。
对基本类型,采用DualPivotQuicksort排序算法,如下:

public static void sort(int[] a) {
    DualPivotQuicksort.sort(a);
}

对Object类型,采用ComparableTimSort排序算法,如下:

public static void sort(Object[] a) {
    if (LegacyMergeSort.userRequested)
        legacyMergeSort(a);
    else
        ComparableTimSort.sort(a);
}

请问这样选择的原因是什么?

伊谢尔伦伊谢尔伦2769 days ago845

reply all(2)I'll reply

  • PHPz

    PHPz2017-04-17 17:12:36

    Expert advice, the reasons are as follows. Merge sort sort() application scenario:

    1. Sort Object types. Quick sort is unstable and has no impact on basic types, but has an impact on Object types. Merge sort is stable.

    2. Sort large arrays. Quick sort's sort() is implemented recursively, and stack overflow will occur when the array size is too large, while merge sort sort() is implemented non-recursively and does not have this problem.

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 17:12:36

    Class sorting, each has different rules. The basic types are either large to small or small to large. But class sorting is completely based on user definition. This is a design pattern

    reply
    0
  • Cancelreply