Insertion sort builds a sorted prefix one value at a time. It shifts larger values one position to the right and inserts the next value into the gap. An already sorted array takes Θ(n) time. Random and reverse-sorted input take Θ(n²) on average and in the worst case, respectively.
Simple example
Insert 1 before 3, then slide 3 aside again to insert 2. Print the sorted values.
Start3 1 2
Result1 2 3
lesson.rb
values = [3, 1, 2]
i = 1
while i < 3
key = values[i]
j = i - 1
while (j >= 0) && (values[j] > key)
values[j + 1] = values[j]
j -= 1
end
values[j + 1] = key
i += 1
end
i = 0
while i < 3
puts values[i]
i += 1
end
Output
1
2
3
Everyday examples
Place a new ticket
A clerk keeps tickets 2, 5 and 8 in order. Where should ticket 6 go?
Start2 5 8 +6
Result2 5 6 8
Slide 8 right. The open spot after 5 is the insertion position.
Add a morning appointment
Your diary starts at 10 and 12. Add an appointment at 9.
Start10 12 +9
Result9 10 12
Both later appointments shift one position to make room.
Append a late payment
A sorted ledger ends with days 4 and 6. A payment for day 7 arrives. What shifts?
Start4 6 +7
Result4 6 7
The last existing day already precedes 7. Append it without shifting the other entries.
Cost and limits
Insertion sort works well on short or nearly sorted lists. Reverse order requires O(n²) moves and comparisons.
Time Complexity
Best case: Θ(n)
Average case: Θ(n²)
Worst case: Θ(n²)
Insertion Sort Implementation in Ruby
Ruby source code
class InsertionSortExample
def insertionSort(arr)
for i in 1...arr.length do
temp = arr[i]
holePosition = i
while(holePosition > 0 && arr[holePosition - 1] > temp)
arr[holePosition] = arr[holePosition - 1]
holePosition = holePosition - 1
end
arr[holePosition] = temp
end
end
def printArray(arr)
for i in 0...arr.length do
print(arr[i].to_s + " ")
end
puts("")
end
end
obj = InsertionSortExample.new
arr = [15, 3, 12, 6, -9, 9, 0]
print("Before Sorting: ")
obj.printArray(arr)
obj.insertionSort(arr)
print("After Sorting: ")
obj.printArray(arr)
Output
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
Advertisements
Walk through the example
Start with [15, 3, 12, 6, -9, 9, 0].
Start with 15 as the sorted prefix. Save the next value, 3.
Shift 15 one place to the right and insert 3 at the start. The prefix is now [3, 15].
For each remaining value, shift only larger values before inserting it. Equal values keep their original order.
Insertion Sort Implementation in Ruby with explanation
Ruby source code
class InsertionSortExample
def insertionSort(arr)
# Un-sorted array from position 1 to length -1
for i in 1...arr.length do
# Take the left most item in an un-sorted array to temp variable
temp = arr[i]
# Mark the left most position as empty or hole
holePosition = i
# Traverse the sorted array from right to left direction
# Move the item from the sorted array to the empty position (i.e. holePosition) only if the temp variable is less then
# Mark the current item's position as empty by decrementing the value by one
while(holePosition > 0 && arr[holePosition - 1] > temp)
arr[holePosition] = arr[holePosition - 1]
holePosition = holePosition - 1
end
# Once the comparison done, move the value in temp variable to the lastly marked empty position
arr[holePosition] = temp
end
end
def printArray(arr)
# Loop the item and print each item in the console with white space seperated
for i in 0...arr.length do
print(arr[i].to_s + " ")
end
puts("")
end
end
obj = InsertionSortExample.new
arr = [15, 3, 12, 6, -9, 9, 0]
print("Before Sorting: ")
obj.printArray(arr)
obj.insertionSort(arr)
print("After Sorting: ")
obj.printArray(arr)
Output
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15