Why does Java 6 Arrays#sort(Object[]) change from mergesort to insertionsort for small arrays?

后端 未结 3 1616
慢半拍i
慢半拍i 2020-12-15 04:42

Java 6\'s mergesort implementation in Arrays.java uses an insertion-sort if the array length is less than some threshold. This value is hard-coded to 7. As th

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-15 05:39

    Insertion sort is n(n-1)/2 and merge sort is n*(log n with base 2 ).

    Considering this -

    1. For Array of Length 5 => Insetion sort = 10 and merge sort is 11.609
    2. For Array of Length 6 => Insetion sort = 15 and merge sort is 15.509
    3. For Array of Length 7 => Insetion sort = 21 and merge sort is 19.651
    4. For Array of Length 8 => Insetion sort = 28 and merge sort is 24

    From above data it is clear, till length 6, insetion sort is faster and after 7, merge sort is efficient.

    That explains why 7 is used.

提交回复
热议问题