Friday, November 22, 2013

Selection Sort - Ruby snippet

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


#selection_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 0..array.length-1
# initialize to the current element
smallest = array[i]
index = i

    for j in i..array.length-1
    #find the smallest element on the RHS of current element
    if array[j] < smallest
     smallest = array[j]
        index = j
    end
    end

#swap the smallest element with the current element
tmp = array[i]
array[i] = smallest
array[index] = tmp
end


p "Sorted array:"
array.each do |x|
p x.to_i
end


Sample Run:-

>>ruby selection_sort.rb 8 5 7 1 9 3
"Input array:"
8
5
7
1
9
3
"Sorted array:"
1
3
5
7
8
9

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