Insertion Sort in Ruby – Code snippet

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]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s