Skip to main content

πŸ”ƒ Sorting

One-line summary: Rearrange elements in order β€” the prerequisite for binary search, two pointers, and many greedy algorithms.


Enhanced Visualization​

Enhanced Sorting Algorithm Comparison Interactive comparison of Bubble Sort, Quick Sort, and Merge Sort with real-time performance metrics

Sorting Flow Sorting GIF

Algorithm Analysis​

The enhanced animation above demonstrates three fundamental sorting paradigms:

πŸ”΄ Bubble Sort - Simple but Inefficient​

  • Strategy: Compare adjacent elements and swap if out of order
  • Performance: ~500,000 operations for n=1000 elements
  • Visual: Watch elements "bubble" to their correct positions
  • Best for: Educational purposes, very small datasets

🟣 Quick Sort - Efficient Divide-and-Conquer​

  • Strategy: Choose pivot, partition around it, recursively sort
  • Performance: ~10,000 operations for n=1000 elements
  • Visual: See pivot selection and partitioning phases
  • Best for: General-purpose sorting, in-place requirements

πŸ”΅ Merge Sort - Stable and Predictable​

  • Strategy: Divide array, sort halves, merge sorted results
  • Performance: ~10,000 operations for n=1000 elements
  • Visual: Observe divide-and-conquer with merging phases
  • Best for: Stable sorting, linked lists, external sorting

Complete Algorithm Comparison​

AlgorithmTime (avg)Time (worst)SpaceStable?
Bubble SortO(nΒ²)O(nΒ²)O(1)Yes
Selection SortO(nΒ²)O(nΒ²)O(1)No
Insertion SortO(nΒ²)O(nΒ²)O(1)Yes
Merge SortO(n log n)O(n log n)O(n)Yes
Quick SortO(n log n)O(nΒ²)O(log n)No
Heap SortO(n log n)O(n log n)O(1)No
Counting SortO(n + k)O(n + k)O(k)Yes
Radix SortO(nk)O(nk)O(n+k)Yes

Cyclic Sort: for arrays containing numbers in range [1..n] β€” place each number at index num-1 in O(n), O(1) space.


Common Patterns​

Merge Sort​

function mergeSort(arr) {
if (arr.length <= 1) return arr;
const mid = Math.floor(arr.length / 2);
return merge(mergeSort(arr.slice(0, mid)), mergeSort(arr.slice(mid)));
}
function merge(left, right) {
const result = [];
let i = 0, j = 0;
while (i < left.length && j < right.length)
result.push(left[i] <= right[j] ? left[i++] : right[j++]);
return result.concat(left.slice(i), right.slice(j));
}

Cyclic Sort​

function cyclicSort(nums) {
let i = 0;
while (i < nums.length) {
const correct = nums[i] - 1;
if (nums[i] !== nums[correct]) [nums[i], nums[correct]] = [nums[correct], nums[i]];
else i++;
}
return nums;
}

Pitfalls​

  • Quick sort worst case O(nΒ²) on sorted input β€” use random pivot or 3-way partition
  • Stable vs unstable: use stable sort when equal elements must maintain relative order
  • JS Array.sort() is not guaranteed stable in older engines (ES2019+ guarantees it)

Practice Problems​

ProblemDifficultySolution
LC 75 β€” Sort ColorsMedium
LC 912 β€” Sort an ArrayMedium
LC 148 β€” Sort ListMedium
LC 179 β€” Largest NumberMedium
LC 315 β€” Count of Smaller Numbers After SelfHard
CC β€” Turbo Sort (TSORT)Easy
CC β€” Inversion Count (INVCNT)Medium
CC β€” Smallest Difference (SMASTR)Easy
LC 164 β€” Maximum GapHard
LC 905 β€” Sort Array By ParityEasy
LC 1636 β€” Sort Array by Increasing FrequencyEasy
LC 56 β€” Merge IntervalsMedium
LC 57 β€” Insert IntervalMedium
LC 147 β€” Insertion Sort ListMedium
LC 215 β€” Kth Largest Element in an ArrayMedium
LC 242 β€” Valid AnagramEasy
LC 252 β€” Meeting RoomsEasy
LC 253 β€” Meeting Rooms IIMedium
LC 274 β€” H-IndexMedium
LC 324 β€” Wiggle Sort IIMedium
LC 347 β€” Top K Frequent ElementsMedium
LC 349 β€” Intersection of Two ArraysEasy
LC 350 β€” Intersection of Two Arrays IIEasy
LC 435 β€” Non-overlapping IntervalsMedium
LC 451 β€” Sort Characters By FrequencyMedium
LC 506 β€” Relative RanksEasy
LC 561 β€” Array PartitionEasy
LC 692 β€” Top K Frequent WordsMedium
LC 791 β€” Custom Sort StringMedium
LC 853 β€” Car FleetMedium
LC 922 β€” Sort Array By Parity IIEasy
LC 973 β€” K Closest Points to OriginMedium
LC 1122 β€” Relative Sort ArrayEasy
LC 1365 β€” How Many Numbers Are Smaller Than CurrentEasy
CC β€” Merge Sort (MERGSORT)Medium
CC β€” Quick Sort (QUICKSRT)Medium
CC β€” Counting Sort (CNTSORT)Easy

  • Binary Search β€” requires sorted input
  • Two Pointers β€” converging pointers need sorted array
  • Heap β€” heapsort; partial sort for Top-K

← Back to Home Β· Β© sparshjaswal