Friday, November 22, 2013

Insertion Sort - Ruby

In this post I mentioned about insertion sort. Below is the code snippet in ruby.

#insertion_sort.rb
array = []
i = 0

#convert string array into integer array
ARGV.each do |x|
array[i] = x.to_i
i = i + 1
end

p "Input Array:"
array.each do |x|
p x
end


for i in 1..array.length-1

current = array[i] #set the current element

j = i-1 #the element just to the left of current element
index = i

while current < array[j] && j >= 0
  array[j+1] = array[j]
  index = j #save the position where the element will be inserted
  j = j-1
end
array[index] = current

#Below method is not efficient! 

=begin
  (i-1).downto(0) do |j|
      if current < array[j]
        #shift the element as in card game
         array[j+1] = array[j]
        array[j] = current
      end
  end
=end

end


p "New Array:"
array.each do |x|
p x.to_i
end


Sample Run:-

>>ruby insertion_sort.rb 9 8 1 25 0
"Input Array:"
9
8
1
25
0
"New Array:"
0
1
8
9
25

No comments:

Post a Comment