Quicksort in Groovy

Quicksort partitions the input around a pivot and recursively sorts the two sides. This implementation uses the first value as its pivot. Balanced partitions give Θ(n log n) time. Repeatedly choosing an extreme value gives Θ(n²) time, including on already sorted input with this pivot rule.

Simple example

Choose 2 as the pivot. Move 1 to its left and 3 to its right. Each side now has one item.

Start3 1 2
Result1 2 3
Lesson.groovy
def values = [3, 1, 2]
def pivot = values[2]
def boundary = 0
def i = 0
while (i < 2) {
    if (values[i] < pivot) {
        def saved = values[i]
        values[i] = values[boundary]
        values[boundary] = saved
        boundary += 1
    }
    i += 1
}
values[2] = values[boundary]
values[boundary] = pivot
i = 0
while (i < 3) {
    println(values[i])
    i += 1
}
Output
1
2
3

Everyday examples

Divide parcels by a sample weight

Weights are 8, 2 and 5 kilograms. Use 5 as the pivot. What goes on each side?

Start8 2 5
Result2 • 5 • 8

Two is lighter and eight is heavier. The pivot now separates the two groups.

Handle equal book prices

Every book costs 4. What would a three-way partition produce?

Start4 4 4
Result∅ • 4 4 4 • ∅

The equal group contains every book. Neither outer group needs more work.

Notice a poor pivot

Dates 1, 2, 3 and 4 are in order. Always choose the last date. What happens on the first split?

Start1 2 3 4
Result1 2 3 • 4 • ∅

One group still holds three items. Repeating this pattern wastes comparisons.

Cost and limits

Balanced partitions usually lead to O(n log n) work. Repeatedly choosing an extreme pivot can take O(n²).

Time Complexity

  • Best case: Θ(n log n)
  • Average case: Θ(n log n)
  • Worst case: Θ(n²)