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 Lua 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.lua
Replay: real traced execution (multi-file project)
local arr = {5, 1, 4, 2, 8}
for i = 2, #arr do
	local key = arr[i]
	local j = i - 1
	while j >= 1 and arr[j] > key do
		arr[j + 1] = arr[j]
		j = j - 1
	end
	arr[j + 1] = key
end
io.write("[")
for k = 1, #arr do
	if k > 1 then io.write(", ") end
	io.write(tostring(arr[k]))
end
io.write("]\n")
  1. arr ← [5, 1, 4, 2, 8]

    1local arr = {5, 1, 4, 2, 8}2for i = 2, #arr do
    values this step[5, 1, 4, 2, 8]arr
  2. arr ← [1, 5, 4, 2, 8]

    2for i = 2, #arr do3	local key = arr[i]4	local j = i - 1
    values this step[5, 1, 4, 2, 8] [1, 5, 4, 2, 8]arr1key
  3. arr ← [1, 4, 5, 2, 8]

    4local j = i - 15while j >= 1 and arr[j] > key do6	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]

    4local j = i - 15while j >= 1 and arr[j] > key do6	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]

    1local arr = {5, 1, 4, 2, 8}2for i = 2, #arr do
    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

  • local arr = {5, 1, 4, 2, 8} is a Lua table sorted in place.
  • Lua uses 1-based indexes here, so the outer loop is for i = 2, #arr do.
  • Each pass saves local key = arr[i] before shifting any table slots.
  • local j = i - 1 starts at the right edge of the already-sorted prefix.
  • The inner guard is while j >= 1 and arr[j] > key do, which both protects the lower bound and tests whether a value must shift right.
  • Shifting is the assignment arr[j + 1] = arr[j], followed by j = j - 1.
  • After shifting stops, arr[j + 1] = key writes the saved value into its insertion slot.
  • The trace shows 1 inserted before 5, producing [1, 5, 4, 2, 8].
  • It then shifts 5 to insert 4, producing [1, 4, 5, 2, 8], and shifts 5 and 4 to insert 2, producing [1, 2, 4, 5, 8].
  • The final io.write loop prints the table as [1, 2, 4, 5, 8].