Java & Merge Sort

Why does Java impl choose merge sort by quick sort? and why do they copy the contents to an array?

API: “The sorting algorithm is a modified merge system (in which merging is omitted if the highest element in the lower sublist is smaller than the smallest element in the upper sublist). This algorithm ensures guaranteed performance n log (n) This implementation unloads the specified list into an array, sorts the array and iterates through the list, dropping each item from the corresponding position in the array, which avoids the performance n2 log (n) that would occur when trying to sort the linked list by place. "

+3
source share
4 answers

The Java guys exchanged the worst case scenario for avg, as you probably know, quicksort could work in O (n ^ 2) in the worst case.

You can read in the API, sorting a linked list in place is more difficult n ^ 2log (n)

Merge sort is stable, which is not true for the efficient version of quicksort. (which can be very important when sorting objects + many programmers accept this as provided when they use Collections.sort ())

+7
source

The documentation answers both questions:

This algorithm provides guaranteed performance n log (n).

Merge sort does not have pathological cases of quick sort

quicksort , ; quicksort . (, , ).

n 2 log (n) .

, . , , RandomAccess , , RandomAccess 1.4.

+6

, , mergesort, , .

n log n, , , , , . Arrays.sort, quicksort, Object[] mergesort. , ; .

+4
  • O (n log n). O (n ^ 2). , .

  • This sort of sort, such as quick sort, does not work in linked lists, as your quote mentions. To work predictably for all types of collections, a copy is needed.

  • Quick sorting itself is unstable. Stability is sometimes desirable and something the API has to offer.

0
source

Source: https://habr.com/ru/post/1757525/


All Articles