Show 25 50 100
PDF
8 result(s) in Sort Clear

Index

Showing 8 topics
  1. Sorting Algorithms Comparison
  2. Bubble Sort
  3. Selection Sort
  4. Insertion Sort
  5. Merge Sort
  6. Quick Sort
  7. Heap Sort
  8. Counting Sort
1 Index
AlgorithmBestAverageWorstSpaceStable
Bubble SortO(n)O(n²)O(n²)O(1)Yes
Selection SortO(n²)O(n²)O(n²)O(1)No
Insertion SortO(n)O(n²)O(n²)O(1)Yes
Merge SortO(n log n)O(n log n)O(n log n)O(n)Yes
Quick SortO(n log n)O(n log n)O(n²)O(log n)No
Heap SortO(n log n)O(n log n)O(n log n)O(1)No
Counting SortO(n + k)O(n + k)O(n + k)O(k)Yes

Stable = equal elements keep their original order. In-place = O(1) extra memory. C++ sort() uses Introsort (quick + heap + insertion), O(n log n).

2 Index

Repeatedly swap adjacent elements that are in the wrong order; after each pass the largest element "bubbles" to the end. Stop early if a pass makes no swap.

C++ 12 lines
void bubbleSort(int a[], int n) {
    for (int i = 0; i < n - 1; i++) {
        bool swapped = false;
        for (int j = 0; j < n - 1 - i; j++) {
            if (a[j] > a[j + 1]) {
                swap(a[j], a[j + 1]);
                swapped = true;
            }
        }
        if (!swapped) break;   // already sorted → O(n) best case
    }
}
3 Index

Find the minimum of the unsorted part and put it at the front. Always O(n²) comparisons but at most n − 1 swaps.

C++ 8 lines
void selectionSort(int a[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int minIdx = i;
        for (int j = i + 1; j < n; j++)
            if (a[j] < a[minIdx]) minIdx = j;
        swap(a[i], a[minIdx]);
    }
}
4 Index

Take the next element and insert it into its correct place in the already-sorted left part, like sorting playing cards. Very fast for small or nearly-sorted arrays.

C++ 11 lines
void insertionSort(int a[], int n) {
    for (int i = 1; i < n; i++) {
        int key = a[i];
        int j = i - 1;
        while (j >= 0 && a[j] > key) {
            a[j + 1] = a[j];   // shift right
            j--;
        }
        a[j + 1] = key;
    }
}
5 Index

Divide and conquer: split the array into halves, sort each half recursively, then merge the two sorted halves. Always O(n log n), stable, needs O(n) extra space.

Split down to single elements, then merge back in order

Split down to single elements, then merge back in order

C++ 17 lines
void merge(vector<int> &a, int l, int m, int r) {
    vector<int> tmp;
    int i = l, j = m + 1;
    while (i <= m && j <= r)
        tmp.push_back(a[i] <= a[j] ? a[i++] : a[j++]);
    while (i <= m) tmp.push_back(a[i++]);
    while (j <= r) tmp.push_back(a[j++]);
    for (int k = 0; k < tmp.size(); k++) a[l + k] = tmp[k];
}

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

Recurrence: T(n) = 2T(n/2) + O(n) → O(n log n).

6 Index

Pick a pivot, partition the array so smaller elements are on the left and larger on the right, then sort both sides recursively. Average O(n log n), in-place. Worst case O(n²) when the pivot is always the smallest/largest (e.g. already sorted input with last-element pivot); a random pivot avoids it.

After one partition the pivot is at its final index

After one partition the pivot is at its final index

C++ 16 lines
int partition(vector<int> &a, int low, int high) {   // Lomuto
    int pivot = a[high];
    int i = low - 1;
    for (int j = low; j < high; j++)
        if (a[j] < pivot) swap(a[++i], a[j]);
    swap(a[i + 1], a[high]);
    return i + 1;
}

void quickSort(vector<int> &a, int low, int high) {
    if (low < high) {
        int p = partition(a, low, high);
        quickSort(a, low, p - 1);
        quickSort(a, p + 1, high);
    }
}

Q & A

  1. Merge sort vs quick sort?
    Merge sort: always O(n log n), stable, needs O(n) extra memory, good for linked lists and external sorting. Quick sort: in-place and usually faster in practice, but O(n²) in the worst case and not stable.
7 Index

Build a max-heap, then repeatedly move the root (largest) to the end and re-heapify the rest. O(n log n) always, in-place, not stable.

C++ 18 lines
void heapify(vector<int> &a, int n, int i) {
    int largest = i, l = 2 * i + 1, r = 2 * i + 2;
    if (l < n && a[l] > a[largest]) largest = l;
    if (r < n && a[r] > a[largest]) largest = r;
    if (largest != i) {
        swap(a[i], a[largest]);
        heapify(a, n, largest);
    }
}

void heapSort(vector<int> &a) {
    int n = a.size();
    for (int i = n / 2 - 1; i >= 0; i--) heapify(a, n, i);   // build heap O(n)
    for (int i = n - 1; i > 0; i--) {
        swap(a[0], a[i]);          // largest to the end
        heapify(a, i, 0);
    }
}
8 Index

Non-comparison sort for small integer ranges: count each value, then write them back in order. O(n + k) where k is the value range.

C++ 7 lines
void countingSort(vector<int> &a, int maxVal) {
    vector<int> cnt(maxVal + 1, 0);
    for (int x : a) cnt[x]++;
    int idx = 0;
    for (int v = 0; v <= maxVal; v++)
        while (cnt[v]--) a[idx++] = v;
}