Skip to content
uencoder

Sorting Algorithm

Sorting algorithms arrange elements in order—quicksort, merge sort, and heapsort are common—with complexity ranging from O(n log n) to O(n²).

Purpose

To order unordered data, the basis of searching, deduplication, and display.

Mechanism

Comparison sorting has an O(n log n) lower bound. Quicksort averages O(n log n), worst case O(n²), in place. Merge sort is O(n log n), stable, but needs O(n) space. Heapsort is O(n log n) in place. Counting/radix sorts are non-comparison and can be O(n). Stable sorts preserve the relative order of equal elements.

Use cases

  • Database ORDER BY
  • Preprocessing before search
  • Rankings and leaderboards
  • Deduplication (sort + adjacent comparison)

Examples

  • Input
    [3,1,4,1,5] → quicksort
    Output
    [1,1,3,4,5]

    O(n log n) average

Common errors

Quicksort recursion overhead is high for small arrays
Use insertion sort for small arrays (a quicksort optimization)

Related terms

Related tools

References