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

Basic Implementation

basic.rs
fn main() {
	let mut arr = [5, 1, 4, 2, 8];
	for i in 1..arr.len() {
		let key = arr[i];
		let mut j = i;
		while j > 0 && arr[j - 1] > key {
			arr[j] = arr[j - 1];
			j -= 1;
		}
		arr[j] = key;
	}
	println!("{:?}", arr);
}

Complexity

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

Implementation notes

  • The checked source uses a fixed mutable array, let mut arr = [5, 1, 4, 2, 8], not a Vec.
  • The outer loop is for i in 1..arr.len(), so i is a usize index that stays inside the array's bounds.
  • let key = arr[i] copies the current i32 value before any shifts overwrite that slot. let mut j = i tracks the insertion position with a usize.
  • The shift guard is ordered as j > 0 && arr[j - 1] > key, so j - 1 is only evaluated after proving j is nonzero.
  • Each shift copies one scalar right with arr[j] = arr[j - 1], then decrements j; after the loop, arr[j] = key writes the saved value into the gap.
  • The trace records [5, 1, 4, 2, 8], then inserting 1 before 5, shifting 5 for key 4, shifting 5 and 4 for key 2, and ending at [1, 2, 4, 5, 8].
  • println!("{:?}", arr) uses Rust's debug formatter for the fixed array and prints [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.