Sorting and searching · Exercise 58 of 100

Quicksort

Choose a value called the pivot and group the values by whether they are smaller than, equal to, or larger than the pivot. The equal values already belong between the two outer groups. Sort each outer group the same way if it has at least two values, then join the groups in order.

Try it yourself

Apply this three-group quicksort to [4, 2, 4, 1, 3]. Keep the original order within each group and choose its first value as the pivot whenever a group has at least two values. How many times do you choose a pivot?

One-step hint

Sketch the three groups around the first pivot. Mark a new pivot only in an outer group that still contains at least two values.

Worked solution
  1. Choose 4 first. The smaller group is [2, 1, 3], the equal group is [4, 4], and the larger group is empty.
  2. Choose 2 for [2, 1, 3]. Its outer groups are [1] and [3], so neither needs another pivot. The two pivot choices were 4 and 2.
DSA compiler