Build the sorted prefix one item at a time, shifting larger values right until the current key can be inserted.

Algorithm

The checked-in replay follows the same small input and final output across all 21 DSA books, so this Dart DSA implementation can be compared directly with the other languages.

sorted prefix Positions before the scan index are already sorted.
shifting Larger values move one slot right to make room for the key.

Basic Implementation

basic.dart
Replay: real traced execution (multi-file project)
void main() {
  final arr = <int>[5, 1, 4, 2, 8];
  for (var i = 1; i < arr.length; i++) {
    final key = arr[i];
    var j = i - 1;
    while (j >= 0 && arr[j] > key) {
      arr[j + 1] = arr[j];
      j--;
    }
    arr[j + 1] = key;
  }
  print(arr);
}
  1. arr ← [5, 1, 4, 2, 8]

    1void main() {2  final arr = <int>[5, 1, 4, 2, 8];
    values this step[5, 1, 4, 2, 8]arr
  2. arr ← [1, 5, 4, 2, 8]

    3for (var i = 1; i < arr.length; i++) {4  final key = arr[i];5  var j = i - 1;
    values this step[5, 1, 4, 2, 8] [1, 5, 4, 2, 8]arr1key
  3. arr ← [1, 4, 5, 2, 8]

    5var j = i - 1;6while (j >= 0 && arr[j] > key) {7  arr[j + 1] = arr[j];
    values this step[1, 5, 4, 2, 8] [1, 4, 5, 2, 8]arr4key
  4. arr ← [1, 2, 4, 5, 8]

    5var j = i - 1;6while (j >= 0 && arr[j] > key) {7  arr[j + 1] = arr[j];
    values this step[1, 4, 5, 2, 8] [1, 2, 4, 5, 8]arr2key
  5. stdout ← [1, 2, 4, 5, 8]

    11  }12  print(arr);13}
    values this step[1, 2, 4, 5, 8]stdout[1, 2, 4, 5, 8]arr

Complexity

  • Time: O(n^2) worst and average, O(n) best
  • Space: O(1)
  • Stable: yes

Implementation notes

  • Keep the explicit algorithmic steps instead of calling a standard-library sort. The replay is meant to expose comparisons, movement, and recursion.
  • The implementation is intentionally compact for learning and replay, not a production sorting utility.