34.1 Sorting Summary

Other Desirable Sorting Properties: Stability

A sort is said to be stable if order of equivalent items is preserved.

Equivalent items don’t ‘cross over’ when being stably sorted.

On the other hand...

Sorting instability can be really annoying! Wanted students listed alphabetically by section.

Arrays.sort()

In Java, Arrays.sort(someArray) uses:

  • Mergesort (specifically the TimSort variant) if someArray consists of Objects.

  • Quicksort if someArray consists of primitives.

Why?
  • Quicksort isn’t stable, but there’s only one way to order them. Wouldn’t have multiple types of orders.

  • Could sort by other things, say the sum of the digits.

  • Order by the number of digits.

  • My usual answer: 5 is just 5. There are no different possible 5's.

  • When you are using a primitive value, they are the ‘same’. A 4 is a 4. Unstable sort has no observable effect.

  • There’s really only one natural order for numbers, so why not just assume that’s the case and sort them that way.

  • By contrast, objects can have many properties, e.g. section and name, so equivalent items CAN be differentiated.

  • If you know there’s only one way, can you force Java to use Quicksort?

Sorting

Sorting is a foundational problem.

  • Obviously useful for putting things in order.

  • But can also be used to solve other tasks, sometimes in non-trivial ways.

    • Sorting improves duplicate findings from a naive N^2 to N log N.

    • Sorting improves 3SUM from a naive N^3 to N^2.

  • There are many ways to sort an array, each with its own interesting tradeoffs and algorithmic features.

Today we’ll discuss the fundamental nature of the sorting problem itself: How hard is it to sort?

Sorts Summary

Last updated