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 Swift DSA implementation can be compared directly with the other languages.

Basic Implementation

basic.swift
var arr = [5, 1, 4, 2, 8]
for i in 1..<arr.count {
	let key = arr[i]
	var j = i - 1
	while j >= 0 && arr[j] > key {
		arr[j + 1] = arr[j]
		j -= 1
	}
	arr[j + 1] = key
}
print(arr)

Complexity

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

Implementation notes

  • Swift stores the input in var arr = [5, 1, 4, 2, 8], so the [Int] array is mutable and sorted in place.
  • The outer loop uses for i in 1..<arr.count, leaving index 0 as the initial sorted prefix.
  • let key = arr[i] copies the current Int before shifts overwrite array slots; var j = i - 1 tracks the left scan position.
  • The while condition j >= 0 && arr[j] > key checks the lower bound before reading arr[j], and uses strict Int comparison for stable behavior.
  • Shifts are direct assignments, arr[j + 1] = arr[j], followed by the final placement arr[j + 1] = key; there is no swap helper or extra array.
  • The trace records [5, 1, 4, 2, 8], then [1, 5, 4, 2, 8], [1, 4, 5, 2, 8], and finally [1, 2, 4, 5, 8].
  • print(arr) uses Swift's array display form and outputs [1, 2, 4, 5, 8].
sorted prefix Positions before the scan index are already sorted.
shifting Larger values move one slot right to make room for the key.