SHARE
TWEET

Selection Sort - Ruby

oaktree Mar 19th, 2016 (edited) 35 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #! /usr/bin/env ruby
  2.  
  3. # just input, ignore
  4. puts "give me a string"
  5. str = gets.chomp.split('')
  6. strlen = str.length
  7. # end of input section, stop ignoring
  8.  
  9. # begin sorting
  10. for i in 0...strlen
  11.     min_pos = i # assume the min element is the first element in the unsorted section of str
  12.  
  13.     for j in i+1...strlen # now loop through str, starting from i+1 since there is no need to reevaluate str[i]
  14.         min_pos = j if (str[j] < str[min_pos]) # update min_pos if we find a smaller element
  15.     end
  16.    
  17.     # now we swap them IF AND ONLY IF the smallest element in the unsorted portion of the array is not in its place yet
  18.     # below you'll see the Ruby syntax for swapping two variables' values... it might look strange, but it actually
  19.     # makes it stupidly simple
  20.     str[i] , str[min_pos] = str[min_pos] , str[i] if min_pos != i
  21. end
  22.  
  23. puts str.join('')
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top