DEV Community

Cover image for Dual Pivot Quick Sort: Java’s default sorting algorithm for primitive data types.

Dual Pivot Quick Sort: Java’s default sorting algorithm for primitive data types.

Awdesh on July 29, 2018

What happens when we do Arrays.sort() in Java? which sorting algorithm does Java use in the background? Since Java 7 release back in 2011, defaul...
Collapse
 
qm3ster profile image
Mihail Malo

Regarding the number of elements are <= 47, does this only happen if the whole array .sort() is called on is <= 47, or does the DualPivotQuickSort algorithm use Insertion Sort to sort partitions of length <= 47 instead of recursing DPQS on it??

Collapse
 
s_awdesh profile image
Awdesh • Edited

DualPivotQuickSort class has a threshold of '47' defined for number of elements in an array. If number of elements are lesser than threshold then sorting function uses insertion sort.

Below snippet is from Java docs.

private static final int INSERTION_SORT_THRESHOLD = 47;

// Use insertion sort on tiny arrays
 if (length < INSERTION_SORT_THRESHOLD) {
        if (leftmost) {
              ...
              ...
Collapse
 
qm3ster profile image
Mihail Malo

Yeah, but, is this inside or outside the function that recurses?

function DualPivotQuickSort(arr) {
  if (length < INSERTION_SORT_THRESHOLD) { }
  else {
    /* ... */
    [slice1, slice2, slice3].map(DualPivotQuickSort)
  }
}
// vs
function DualPivotQuickSort(arr) {
  if (length < INSERTION_SORT_THRESHOLD) { }
  else {
    function realDPQS(a) {
      /* ... */
      [slice1, slice2, slice3].map(realDPQS)
    }
  }
}
Collapse
 
codemouse92 profile image
Jason C. McDonald

Excellent explanation! This is perhaps my favorite sorting algorithm out there -- I've been studying it on and off for a few years now.

Collapse
 
ballpointcarrot profile image
Christopher Kruse

Awesome visual explainer on this algorithm!

Collapse
 
hiddewie profile image
Hidde Wieringa

Really like the way you explained all the steps using a deck of cards!

Collapse
 
jgamgam profile image
Joaquim

Whats the reason of different languages choosing different sorts? Whats the logic behind that?

Loved the deck approach, nice read!

Collapse
 
dallgoot profile image
dallgoot

an article on dev.to without any code ? ;)

Collapse
 
littleaeinstein profile image
Janz Aeinstein Villamayor

I think there's a correction on the fourth picture (third sub-array). It should be, "Since LP > RP, Swap (LP,RP)".

I also do love that you used cards as a visual explanation. Nice one!!

Collapse
 
s_awdesh profile image
Awdesh

Good catch. I've updated the image now.