🚀
ArkyEdu BLOG TIC
RO Open App
C++ & Algorithms Grades 7–8 · Olympiad 14 min read

C++ Sorting Algorithms for Middle School & Olympiads: Bubble Sort, Selection Sort, Insertion Sort & std::sort() Explained

Sorting an array unlocks more than half of computer science problem patterns: you cannot run O(log n) Binary Search on unsorted data, nor build leaderboards without a sound comparator. Let’s break down the math, step-by-step traces, and C++ templates every student needs.

💬 WhatsApp ← ICT Blog & Guides
Quick Answer (TL;DR)

For classroom benchmarks (N <= 1,000), quadratic O(n²) sorts—early-exit Bubble Sort, Selection Sort, and Insertion Sort—build essential loop and swap intuition. For contests and N >= 10,000, always use std::sort(v, v + n) from <algorithm>, which runs in guaranteed O(n log n) and sorts 100,000 numbers in under 0.03 seconds.

1. Big-O Comparison: Bubble vs. Selection vs. Insertion vs. std::sort()

Not all O(n²) algorithms behave equally on real inputs. Selection Sort minimizes swaps (at most N − 1 writes), whereas Insertion Sort speeds up to O(n) when an array is already nearly sorted.

Performance and properties of standard C++ sorting methods
AlgorithmBest CaseAvg / Worst CaseExtra SpaceStable?Best Use Case
Bubble Sort (early-exit flag)O(n)O(n²)O(1)YesSmall arrays (N ≤ 1,000) or visualizing adjacent swaps
Selection SortO(n²)O(n²)O(1)No (standard)Minimizing the total number of memory writes/swaps
Insertion SortO(n)O(n²)O(1)YesSmall or nearly sorted inputs, or streaming data
Frequency / Counting SortO(n + V)O(n + V)O(V)YesSmall non-negative integers (0 ≤ v[i] ≤ 10⁶)
std::sort() (<algorithm>)O(n log n)O(n log n)O(log n)No (use stable_sort if needed)Olympiads and production code up to N = 1,000,000+

2. Step-by-Step First-Pass Trace on [7, 2, 9, 1, 5]

Multiple-choice exam questions frequently ask how an array looks right after the very first pass (i = 0). Here is how each algorithm transforms [7, 2, 9, 1, 5] after Pass 1:

Array state of [7, 2, 9, 1, 5] right after Pass 1 (ascending order)
AlgorithmPass 1 ActionArray After Pass 1Guaranteed Fixed Element
Bubble SortSwaps adjacent pairs (7,2), (9,1), (9,5), bubbling 9 right[2, 7, 1, 5, 9]9 locked at last index
Selection SortFinds global min (1) and swaps once with v[0]=7[1, 2, 9, 7, 5]1 locked at index 0
Insertion SortInserts v[1]=2 into sorted prefix [7][2, 7, 9, 1, 5]Prefix [2, 7] sorted
Classic Exam Tip

If a test asks „What is the array after 2 passes of Selection Sort?”, simulate exactly 2 iterations of the outer loop—do not write down the fully sorted array.

3. Clean C++ Implementations: Bubble, Selection & Insertion Sort

Below are standard 0-indexed C++ templates. Notice the early-exit boolean flag in Bubble Sort and value-shifting in Insertion Sort instead of costly three-way swaps:

Optimized Bubble, Selection, and Insertion Sort in C++ (0-indexed)
#include <iostream>
#include <utility>
using namespace std;

void bubbleSort(int v[], int n) {
    bool sorted;
    int pass = 0;
    do {
        sorted = true;
        for (int i = 0; i < n - 1 - pass; i++) {
            if (v[i] > v[i + 1]) {
                swap(v[i], v[i + 1]);
                sorted = false;
            }
        }
        pass++;
    } while (!sorted);
}

void selectionSort(int v[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int minIdx = i;
        for (int j = i + 1; j < n; j++) {
            if (v[j] < v[minIdx]) minIdx = j;
        }
        if (minIdx != i) swap(v[i], v[minIdx]);
    }
}

void insertionSort(int v[], int n) {
    for (int i = 1; i < n; i++) {
        int current = v[i];
        int j = i - 1;
        while (j >= 0 && v[j] > current) {
            v[j + 1] = v[j];
            j--;
        }
        v[j + 1] = current;
    }
}
Watch all three algorithms race side by side in the ArkyEdu Visual Algorithms Lab (/laborator-algoritmi/en/).

4. Competitive C++ Secret Weapon: std::sort() & Custom Comparators

From <algorithm>, std::sort() uses Introsort (Quicksort + Heapsort + Insertion Sort), guaranteeing O(n log n) even on adversarial inputs. Writing a custom comparator cmp lets you rank structs across multiple tie-breakers cleanly:

Multi-criteria sorting with std::sort() in C++
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

struct Student {
    string name;
    int score;
};

bool cmp(const Student& a, const Student& b) {
    if (a.score != b.score)
        return a.score > b.score; // Higher score first
    return a.name < b.name;       // Alphabetical tie-breaker
}

int main() {
    Student arr[3] = { {"Elena", 95}, {"Alex", 100}, {"Bogdan", 95} };
    sort(arr, arr + 3, cmp);
    for (int i = 0; i < 3; i++)
        cout << arr[i].name << " " << arr[i].score << "\n";
    return 0;
}
Always use strict < or > in comparators—never <= or >=—to satisfy strict weak ordering.
0-Indexed vs 1-Indexed Range Trap

If your array uses v[1..n], call sort(v + 1, v + n + 1). If it uses v[0..n-1], call sort(v, v + n). Remember the second pointer is exclusive (one past the last element)!

✅ Sorting Submission Checklist

  • Checked N constraint: O(n²) only for N ≤ 1,000; std::sort() or counting array for N > 10,000.
  • Verified array bounds (no v[n] out-of-bounds read/write).
  • Custom comparator returns strict < or >, never <= or >=.
  • Stepped through a small test case in C++ Visual Trace.

❓ Frequently Asked Questions

What is the fastest general-purpose sorting function in C++?
std::sort(v, v + n) from <algorithm> runs in O(n log n) average and worst case. For small bounded integers, a Counting/Frequency array achieves O(n + maxValue).
What does „stable sorting algorithm” mean?
A stable sort (Insertion Sort, Merge Sort, std::stable_sort) preserves the original relative order of elements with equal keys.
Why is Insertion Sort faster in practice than Bubble Sort?
Insertion Sort shifts elements with single assignments instead of performing full 3-step swaps on every adjacent inversion.
Where can I animate sorting algorithms step by step in my browser?
Open the ArkyEdu Visual Algorithms Lab (/laborator-algoritmi/en/) to animate Bubble, Selection, and Insertion Sort synchronized with C++ code.

More Study Guides

← Back to Blog Index