Here is the algorithm of insertion sort in C++ (from tutorial):
void insertionSort(int arr[], int length) {
int i, j, tmp;
for (i = 1; i < length; i++) {
j = i;
while (j > 0 && arr[j - 1] > arr[j]) {
tmp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = tmp;
j--;
}
}
}
and here is what I’m doing in Ruby
a = [12, 1, 18, -3, -2, 66, 31]
puts a
def insertion_sort(source)
source.to_enum.with_index(1).each do |item, i|
j = i
while((j>0) && (source[j-1] > source[j]))
source[j], source[j-1] = source[j-1], source[j]
j -= 1
end
end
end
insertion_sort(a)
puts a
it throws an error of comparison of Fixnum with nil failed (ArgumentError). Probably because of overflow.
What did I do wrong?
In the
C++version you have(i = 1; i < length; i++). Which means, it will not run the last round wherei = length. That would be out of the array.In
ruby, because you set the offset of the index to1, the last round, you would havei = length. Hencesource[length]is out ofsource, so returnsnil.