Popular insertion sort algorithm written in Ruby.
sampleList = [12, 11, 13, 5, 6]
sortedSampleList = []
sampleList.each_with_index do |inputtedItem, inputtedItemIndex|
if sortedSampleList.length == 0
sortedSampleList.insert(0, inputtedItem)
next
end
sortedSampleList.each_with_index do |outputtedItem, outputtedItemIndex|
if inputtedItem < outputtedItem
sortedSampleList.insert(outputtedItemIndex, inputtedItem)
break
elsif outputtedItemIndex == sortedSampleList.length - 1
sortedSampleList.insert(sortedSampleList.length, inputtedItem)
break
end
end
end
p sampleList
p sortedSampleList
The output is the following.
% ruby insertionSort.rb
[12, 11, 13, 5, 6]
[5, 6, 11, 12, 13]