Sorting Algorithms

Sorting Algorithms #

Sorting algorithms organize data in a specific order (ascending or descending). They vary in complexity, stability, and use cases.

Categories #

Based on Comparison #

  • Use element comparisons to sort
  • Lower bound O(n log n) for comparison sorts
  • Stable: Bubble, Insertion, Merge, Tim
  • In-place: Quick, Heap, Bubble, Insertion, Selection

Non-Comparison #

  • Depend on key ranges or key characteristics
  • Can achieve better than O(n log n) for special cases
  • Stable: Counting, Bucket, Pigeonhole

Hybrid #

  • Combine multiple strategies
  • Tim Sort combines merge and insertion

Common Complexity Comparison #

AlgorithmBestAverageWorstSpaceStable
BubbleO(n)O(n²)O(n²)O(1)Yes
InsertionO(n)O(n²)O(n²)O(1)Yes
SelectionO(n²)O(n²)O(n²)O(1)No
MergeO(n log n)O(n log n)O(n log n)O(n)Yes
QuickO(n log n)O(n log n)O(n²)O(log n)No
HeapO(n log n)O(n log n)O(n log n)O(1)No
CountingO(n+k)O(n+k)O(n+k)O(n+k)Yes

When to Use Which Algorithm? #

  • Small datasets (<100 elements): Insertion, Bubble, Selection
  • Large random datasets: Quick (with good pivot), Merge, Heap
  • Limited memory: In-place sorts (Quick, Heap)
  • Stable sort needed: Merge, Bubble, Insertion
  • Pre-sorted data: Insertion, Bubble (optimized versions)
  • Limited range keys: Counting, Radix, Bucket
  • Data types: Primitive types (Quick), Objects (Merge for stability)

Leetcode Problem Patterns #

PatternProblems
Sort Arrays912. Sort an Array
Sort + Search34. Find First and Last Position
Sort + Two Pointers15. 3Sum, 16. 3Sum Closest
Sort + Prefix Sum325. Maximum Size Subarray Sum Equals K
Sort Objects/Lambda179. Largest Number
Counting Sort Tricks274. H-Index
Bucket Sort451. Sort Characters By Frequency
Radix Sort164. Maximum Gap

Implementation Tips #

  1. Java Arrays.sort(): Uses Tim Sort (hybrid merge + insertion)
  2. Java Collections.sort(): Merge sort derivative
  3. Choose based on constraints: Stability, space, time
  4. Avoid unstable sorts when relative order matters