Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def insert_into_sorted_helper(sorted, element, rest)
- if rest.size == 0 then
- # There is nothing left and the element is not inserted yet, so just append it to the list. It has to be larger than every other element
- sorted << element
- elsif rest[0] >= element then
- # The first element of the rest is larger or equal than our element, so we want to insert it JUST before it.
- (sorted << element).concat(rest)
- else
- # The recursion.
- insert_into_sorted_helper(sorted << rest[0], element, rest[1..-1])
- end
- end
- # Insert an element into a already sorted list. The resulting list stays sorted.
- def insert_into_sorted(sorted, element)
- insert_into_sorted_helper([],element,sorted)
- end
- def recursive_sort_helper(sorted, unsorted)
- if unsorted.size == 0 then
- # Unsorted is 0, so everything is sorted
- sorted
- else
- first = unsorted[0]
- rest = unsorted[1..-1]
- # Insert the first element of the unsorted list into the already sorted list and do the recursion on the rest.
- recursive_sort_helper(insert_into_sorted(sorted, first), rest)
- end
- end
- # Sorts a list
- def recursive_sort(unsorted)
- # The empty list ([]) is already sorted, so we can use it as out sorted array
- recursive_sort_helper([],unsorted)
- end
- unsorted = []
- while input = gets.chomp
- break if input.empty?
- unsorted << input.to_i # If you don't do to_i, your input will be saved as strings and the sort will behave differently.
- end
- puts recursive_sort(unsorted)
Add Comment
Please, Sign In to add comment