Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/env ruby
- # get input
- puts "give me a string"
- str = gets.chomp.split('')
- strlen = str.length
- # end get input
- changes_made = false #optimization to reduce time complexity
- for i in 0..(strlen - 2) # vvv
- # 0 thru two less than the length of str, because we never need to see the last element explicitly
- # because we reach later on with str[j+1]
- for j in 0..(strlen - 2)
- if str[j] > str[j+1]
- str[j],str[j+1] = str[j+1],str[j] # Ruby way to swap vars
- changes_made = true # record that a change was made in this runthrough
- end
- end
- break if !changes_made
- # if there were no changes this run, the list is sorted
- # why continue "sorting" if we've already done the job?
- # if there was a change made, set that to false and run through again,
- # unless, of course, we've already gone through
- changes_made = false
- end
- puts str.join('') #print out the result, but first make it a string and not an array
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement