Insertion Sort

Sort an array using the insertion sort algorithm by building a sorted portion one element at a time.

Code

Algorithms
a = arr.dup
(1...a.length).each do |i|
  key = a[i]
  j = i - 1
  while j >= 0 && a[j] > key
    a[j + 1] = a[j]
    j -= 1
  end
  a[j + 1] = key
end
a

Parameters

Array to sort

Server

More Ruby Snippets