DEV Community

Cover image for Selection sort program in ruby
Sourav das
Sourav das

Posted on

Selection sort program in ruby

n=5 # the size of the array
a=Array.new # creating a blank aray

puts "Enter the numbers"
for i in (0...n)
  a << gets.to_i # getting user input and pushing that into the array
end
for i in (0...n)
  min=a[i] # storing the a[i] value in min for tracking the lower value
  loc=i  # storing the i's location
  for j in (i+1...n)
    if a[j]<min
      min=a[j]
      loc=j
    end
  end
  # swapping the lowest no 
  temp=a[i] 
  a[i]=min
  a[loc]=temp
end

puts "The sorted array"
# printing the numbers 
a.each_index do |x|
  print " #{a[x]}"
end
puts
Enter fullscreen mode Exit fullscreen mode

Top comments (0)