TheAlgorithms-Ruby/sorting/bogo_sort.rb

22 lines
442 B
Ruby
Raw Normal View History

2016-08-12 22:11:35 +05:30
class Array
2020-05-14 11:15:53 +09:00
def sorted?
### goes thru array and checks if all elements are in order
2021-02-06 23:05:54 -08:00
(1...length).each do |i|
return false if self[i - 1] > self[i]
2020-05-14 11:15:53 +09:00
end
2021-02-06 23:05:54 -08:00
true
end
2021-02-06 23:05:54 -08:00
2020-05-14 11:15:53 +09:00
def bogosort
### randomly shuffles until sorted
2021-02-06 23:05:54 -08:00
shuffle! until sorted?
self # return sorted array
2020-05-14 11:15:53 +09:00
end
2016-08-12 22:11:35 +05:30
end
2020-10-27 05:35:41 +09:00
if $0 == __FILE__
2021-02-06 23:05:54 -08:00
puts 'Enter a list of numbers separated by space'
2020-10-27 05:35:41 +09:00
str = gets.chomp.split('')
puts str.bogosort.join('')
end