Masters of Computer Science Design and Analysis of Algorithm

Sorting Very large numbers – Insertion Sort in Ruby

  • This is a program for insertion sort
  • The programming language used is ruby
  • Data from the files are read
  • Output is shown in a file
  • Total time taken for sorting is shown

def insertion_sort(array)
for i in 1…(array.length)
puts i
j = i
while j > 0
if array[j-1] > array[j]
temp = array[j]
array[j] = array[j-1]
array[j-1] = temp
else
break
end
j = j – 1
end
end
return array
end

output_file = File.open(“output.txt”, “w+”)
file = File.open(“input.txt”)
data = file.read

array = data.split(“,”).map(&:to_i)
start_time = Time.now.to_i

sorted = insertion_sort(array)

end_time = Time.now.to_i
total_time = end_time – start_time

puts total_time
output_file.write(sorted)

About Author

ICT Byte