Electronics & Telecommunication (University) is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Bubble, selection and insertion sort

Clear, exam-focused notes on bubble, selection and insertion sort: definitions, exact step-by-step derivations of comparisons/swaps, C++ example programs, common mistakes and exam guidance.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Sorting is a basic operation used everywhere in software engineering: from preparing data to speed up search (see Linear and binary search) to building higher-level algorithms (merge sort, quick sort). Bubble, selection and insertion sort are simple comparison-based sorts that are easy to implement, teach algorithm analysis (time/space complexity, stability, in-place), and are still useful for small arrays or as subroutines in advanced sorts.

Key ideas

Define terms before use:

  • Sorting problem: Given an array A of n elements, produce a permutation of A so that elements are in non-decreasing order. Assume elements are comparable and comparisons are total order operations.
  • In-place: An algorithm is in-place if it uses only O(1) extra storage in addition to the input array.
  • Stable sort: A sort is stable if equal elements preserve their input order in the output.
  • Comparison count: number of element-to-element comparisons (we count each time two array elements are compared). Make the counting convention explicit in exam answers.
  • Swap / shift count: either the number of exchanges (swap of two elements) or the number of shifts (moving an element one position). State which you count.

General technique: each of the three algorithms repeatedly makes local decisions to order elements. We derive exact counts using arithmetic sums.

  1. Bubble sort (basic adjacent-swap method)
  • Algorithm idea: Repeatedly sweep the array left-to-right (or right-to-left), comparing adjacent pairs and swapping if out of order. After k passes, the largest k elements are in place (for rightward bubbling).
  • Stability: bubble sort is stable (adjacent swaps preserve relative order of equal items if implementation swaps only when strictly greater).
  • In-place: yes (O(1) extra space).
  • Comparison derivation (basic double-loop version that always runs full passes): For i from 0 to n-2, inner loop does (n-1-i) adjacent comparisons. Total comparisons = sum_{i=0}^{n-2} (n-1-i) = sum_{k=1}^{n-1} k = n(n-1)/2.
  • Swap count: each swap removes exactly one inversion. Worst-case (reverse sorted) number of inversions = n(n-1)/2, so worst-case swaps = n(n-1)/2. For a random permutation, expected number of inversions = n(n-1)/4, so average swaps = n(n-1)/4.
  • Optimized bubble: stop early if no swap occurs in a pass — best case (already sorted) becomes O(n) comparisons and 0 swaps.
  1. Selection sort
  • Algorithm idea: For i from 0 to n-2, find index of minimum element in A[i..n-1] and swap it with A[i].
  • Stability: not stable by default (a swap may move an equal element past another equal element). You can make a stable version by moving the minimum element by shifting instead of swapping, but that costs more shifts.
  • In-place: yes (O(1) extra space).
  • Comparisons: inner loop checks each remaining element to find minimum. For i from 0 to n-2 we perform (n-1-i) comparisons; total = n(n-1)/2. This is independent of input order.
  • Swaps: exactly (n-1) swaps in a straightforward implementation (one swap per outer iteration), but if you avoid swapping when min is already at i, swaps ≤ n-1. (Often universities state swaps = n-1.)
  1. Insertion sort
  • Algorithm idea: Build a sorted prefix A[0..i-1], insert A[i] into correct position by shifting larger elements rightwards. Useful on nearly-sorted data.
  • Stability: insertion sort is stable (it only moves elements greater than key; equal elements can be kept before).
  • In-place: yes, uses O(1) extra space.
  • Best case (already sorted): each insertion compares once to confirm order, so comparisons = n-1 and shifts = 0 → time O(n).
  • Worst case (reverse sorted): for i = 1..n-1, key must be moved to front requiring i moves; total shifts = sum_{i=1}^{n-1} i = n(n-1)/2. Comparisons in the usual accounting that counts each element comparison (including the final failing comparison) also give O(n^2) — exact counts depend on the counting convention. With the standard convention: worst-case comparisons = n(n-1)/2 and shifts = n(n-1)/2.
  • Average case (random order): expected number of shifts = sum_{i=1}^{n-1} (i/2) = n(n-1)/4. If comparisons are counted as shifts plus one failed comparison per insertion, a common approximation is n(n-1)/4 + (n-1); the exact expected comparisons (without a sentinel) are n(n-1)/4 + n - H_n, where H_n is the nth harmonic number.

Exact arithmetic facts used (show derivations on exam):

  • Sum of first m natural numbers: sum_{k=1}^m k = m(m+1)/2. Use with m = n-1.
  • For comparisons in nested loops where inner length reduces by 1 each outer iteration, total comparisons = n(n-1)/2.

How to draw in an exam (diagram): draw a horizontal array of boxes labelled A[0] A[1] ... A[n-1]. Show arrows for comparisons between adjacent boxes (for bubble), show selection of minimum element by circling the candidate min and an arrow to position i (for selection), and show a highlighted key being shifted left through boxes (for insertion). Label passes (pass 1, pass 2, …) and show indices and counts under the diagram.

Assumptions to state in answers:

  • Elements are compared using a single comparison operator (total order).
  • Counting conventions: whether you count element comparisons only, or also the loop/fail comparisons; whether a shift is counted as an assignment or swap. Make this explicit when deriving exact numbers.

Formulas

comparisons_bubble_basic = n(n-1)/2 — number of adjacent comparisons in the straightforward bubble double loop. n is array length, unitless, applies when you always do full passes.

swaps_bubble_worst = n(n-1)/2 — worst-case adjacent swaps (reverse-sorted), equals number of inversions.

expected_inversions_random = n(n-1)/4 — expected number of inversions for a random permutation (used for average swaps in bubble).

comparisons_selection = n(n-1)/2 — comparisons of selection sort (input-order independent).

swaps_selection = n-1 — swaps in selection sort (one per outer iteration, for straightforward implementation).

shifts_insertion_worst = n(n-1)/2 — worst-case shifts for insertion sort (reverse-sorted).

shifts_insertion_avg = n(n-1)/4 — expected shifts for insertion on random input.

time_complexity_all_worst = O(n^2), time_complexity_insertion_best = O(n) — asymptotic running times.

C++ syntax to remember for implementing these sorts: for (int i = 0; i < n; ++i) { ... } — basic for loop std::swap(a[i], a[j]); — swap two elements (include <algorithm>) while (j > 0 && a[j-1] > key) { ... } — typical insertion shifting loop

Worked examples

Below are three complete C++ programs (one per algorithm). Each reads n, then n integers, sorts in non-decreasing order, prints the sorted array and counts (comparisons / swaps or shifts). Sample input and exact output are given.

  1. Bubble sort (optimized: stops when no swaps in a pass)
#include <bits/stdc++.h>
using namespace std;
int main(){
    int n; if(!(cin>>n)) return 0;
    vector<int>a(n); for(int i=0;i<n;++i) cin>>a[i];
    long long comps=0, swaps=0;
    for(int i=0;i<n-1;++i){
        bool swapped=false;
        for(int j=0;j<n-1-i;++j){
            ++comps;
            if(a[j] > a[j+1]){ swap(a[j], a[j+1]); ++swaps; swapped=true; }
        }
        if(!swapped) break;
    }
    for(int x:a) cout<<x<<" "; cout<<"\n";
    cout<<"comparisons="<<comps<<" swaps="<<swaps<<"\n";
}

Sample input: 5 5 4 3 2 1

Exact output: 1 2 3 4 5 comparisons=10 swaps=10

  1. Selection sort
#include <bits/stdc++.h>
using namespace std;
int main(){
    int n; if(!(cin>>n)) return 0;
    vector<int>a(n); for(int i=0;i<n;++i) cin>>a[i];
    long long comps=0, swaps=0;
    for(int i=0;i<n-1;++i){
        int minidx=i;
        for(int j=i+1;j<n;++j){ ++comps; if(a[j] < a[minidx]) minidx = j; }
        if(minidx != i){ swap(a[i], a[minidx]); ++swaps; }
    }
    for(int x:a) cout<<x<<" "; cout<<"\n";
    cout<<"comparisons="<<comps<<" swaps="<<swaps<<"\n";
}

Sample input: 5 5 4 3 2 1

Exact output: 1 2 3 4 5 comparisons=10 swaps=2

  1. Insertion sort
#include <bits/stdc++.h>
using namespace std;
int main(){
    int n; if(!(cin>>n)) return 0;
    vector<int>a(n); for(int i=0;i<n;++i) cin>>a[i];
    long long comps=0, shifts=0;
    for(int i=1;i<n;++i){
        int key = a[i];
        int j = i;
        while(j > 0){
            ++comps; // compare a[j-1] and key
            if(a[j-1] > key){ a[j] = a[j-1]; ++shifts; --j; }
            else break;
        }
        a[j] = key;
    }
    for(int x:a) cout<<x<<" "; cout<<"\n";
    cout<<"comparisons="<<comps<<" shifts="<<shifts<<"\n";
}

Sample input: 5 5 4 3 2 1

Exact output: 1 2 3 4 5 comparisons=10 shifts=10

Notes on these programs: the counting style is explicit: comparisons count each element-to-element comparison; bubble counts adjacent comparisons, selection counts candidate comparisons in the inner loop, insertion counts each time key is compared to a left element. Different papers may use slightly different counting conventions (e.g., count failed loop test), so state your convention in the exam.

Common mistakes

  • Forgetting stability distinctions: claim selection is stable without explaining swap effect.
  • Arithmetic errors on sums: misuse of sum_{k=1}^{n-1} k = n(n-1)/2.
  • For insertion sort, forgetting best-case O(n) when input is already sorted and algorithm checks with single comparisons per insert.

For your exam

Types of questions you will see:

  • Definitions and properties: define stability, in-place, give best/average/worst-case times and space.
  • Short notes: compare the three sorts (stability, swaps, comparisons, when to use).
  • Derivations: show step-by-step derivation that comparisons = n(n-1)/2 for selection and for basic bubble; sum the arithmetic series.
  • Numericals: compute comparisons and swaps for a given small array — show the array state after each pass (draw boxes and indices) and give counts.
  • Programs: write C++ code for any of the sorts; include input/output format and complexity comments.

What a full-marks answer includes:

  • Clear statement of algorithm and assumptions (comparison model, counting rules).
  • Correct derivation of counts using sums and explicit algebra.
  • Diagram or table showing array state across passes for a small example when required.
  • Correct complexity classification in Theta, O and Omega when asked.

Quick check

  1. For n=6, how many comparisons does basic selection sort always perform?
  2. Which of these sorts is stable by default: bubble, selection, insertion?
  3. Expected number of inversions in a random permutation of size n?

Answers: 1) n(n-1)/2 = 15. 2) Bubble and insertion are stable; selection is not (by default). 3) n(n-1)/4.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?