Skip to content

Insertion sort

C++ insertion sort

Flowchart (ISO 5807)

YesNoStartInput a[], ni = 1, n − 1, 1key = a[i]j = i − 1j ≥ 0 and a[j] > keya[j + 1] = a[j]j = j − 1a[j + 1] = keyEndFigure 1 — insertionSort

Source code

C++
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];
            j--;
        }
        a[j + 1] = key;
    }
}

The editor opens with this code — change it and the chart redraws.

Language
C++
Constructs
insertion sort
Topic
Algorithms
Formats
Word, Visio, draw.io, PDF, SVG

Related examples