Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/env ruby
- # just input, ignore
- puts "give me a string"
- str = gets.chomp.split('')
- strlen = str.length
- # end of input section, stop ignoring
- # begin sorting
- for i in 0...strlen
- min_pos = i # assume the min element is the first element in the unsorted section of str
- for j in i+1...strlen # now loop through str, starting from i+1 since there is no need to reevaluate str[i]
- min_pos = j if (str[j] < str[min_pos]) # update min_pos if we find a smaller element
- end
- # now we swap them IF AND ONLY IF the smallest element in the unsorted portion of the array is not in its place yet
- # below you'll see the Ruby syntax for swapping two variables' values... it might look strange, but it actually
- # makes it stupidly simple
- str[i] , str[min_pos] = str[min_pos] , str[i] if min_pos != i
- end
- puts str.join('')
Add Comment
Please, Sign In to add comment