Dual Pivot QuickSort
Last updated
Was this helpful?
Last updated
Was this helpful?
Quciksort is a really great sorting algorithm, but has as a disadvantage that it is easy to get the worst case scenario that causes a performance. Because of this the Dual Pivot QuickSort has come to life that tries to overcome a lot of problems with these problematic datasets.
Remember that this is a complex algorithm if you are not used to working with algorithms, so I would recommend starting with the normal QuickSort first.
To start, we have 2 Pivots called P1 and P2, we then divide the array in 4 parts (see figure). Important to remember is the indexes L, K and G which we will move during the algorithm.
Range for our parts:
Part
Range
Part 1
Left + 1 → L - 1
Part 2
L → K - 1
Part 3
G + 1 → Right - 1
Part 4
K → G (Not processed elements)
Our algorithm:
If PartitionSize < 17 => Use Insertion Sort
Pick 2 Pivots, P1 and P2, mostly P1 = v[0] and P2 = v[v.size() - 1]
If P1 > P2, swap them
Foreach element in Part 4:
If Element < P1 → Swap Element with v[L] and do L++ and K++
If Element > P2 → Swap Element with v[G - 1] and do G--
If P1 ≤ Element ≤ P2 → K++
As long as K ≤ G → Repeat step 4
Swap P1 with last element from Part 1, Swap P2 with first element from Part 3
Repeat steps 1 → 6 For every part 1, 2 and 3
These are a lot of steps, but we can literally follow them and turn them into code.
For the implementation check paragraph §1.4
.
Advantages
Faster than normal QuickSort
Less chance to hit the worst case scenario
Disadvantages
Worst Case
Average Case
Best Case
-
-
-
DELETE: Code
100
1.000
10.000
100.000
1.000.000
Random Elements
-
-
-
-
-
Ascending Elements
-
-
-
-
-
Descending Elements
-
-
-
-
-
Requires less swaps ( average)
Requires more swaps ()