🧮 Sorting Algorithms Master Guide

Sorting is a foundational topic in computer science and interviews. Mastering sorting means understanding the intuition, implementation, and use-cases for each algorithm.

šŸ“‘ Table of Contents

  1. Overview & Keywords
  2. Must-Know Sorting Algorithms
  3. Templates
  4. Key Patterns
  5. Practice Problems

Overview & Keywords

Sorting is the process of arranging data in a particular order (ascending/descending). Common interview keywords:


Must-Know Sorting Algorithms

šŸ”¶ Selection Sort

šŸ”¶ Bubble Sort

šŸ”¶ Insertion Sort

šŸ”¶ Merge Sort

šŸ”¶ Quick Sort

šŸ”¶ Heap Sort

šŸ”¶ Counting Sort

šŸ”¶ Bucket Sort

šŸ”¶ Radix Sort


Templates

Selection Sort

void selectionSort(vector<int>& arr) {
    int n = arr.size();
    for (int i = 0; i < n - 1; i++) {
        int minIndex = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIndex]) minIndex = j;
        }
        swap(arr[i], arr[minIndex]);
    }
}

Merge Sort

void mergeSort(vector<int>& arr, int l, int r) {
    if (l >= r) return;
    int mid = l + (r - l) / 2;
    mergeSort(arr, l, mid);
    mergeSort(arr, mid+1, r);
    merge(arr, l, mid, r);
}

Quick Sort (Lomuto)

int partition(vector<int>& a, int l, int r) {
    int pivot = a[r];
    int i = l;
    for (int j = l; j < r; j++) {
        if (a[j] < pivot) {
            swap(a[i], a[j]);
            i++;
        }
    }
    swap(a[i], a[r]);
    return i;
}

Key Patterns

Pattern Stable Adaptive In-place Used In
Selection Sort āŒ āŒ āœ… Teaching
Bubble Sort āœ… āœ… āœ… Teaching
Insertion Sort āœ… āœ… āœ… TimSort, STL
Merge Sort āœ… āŒ āŒ stable_sort(), Linked
Quick Sort āŒ āŒ āœ… STL sort(), Introsort
Heap Sort āŒ āŒ āœ… Priority Queue
Counting Sort āœ… āŒ āœ… Bucket/Dutch Flag
Bucket Sort āœ… āŒ āœ… Max Gap, Floats
Radix Sort āœ… āŒ āœ… Phone Numbers, Strings

Practice Problems

Level 1 — Basics

Level 2 — Medium

148 āœ“ Solved

Level 3 — Hard

23 ā—‹ Unsolved
164 ā—‹ Unsolved

← Back to Searching & Sorting DSA Hub šŸ