Guest User

Untitled

a guest
Jul 22nd, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. def insert_into_sorted_helper(sorted, element, rest)
  2.  
  3. if rest.size == 0 then
  4. # 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
  5. sorted << element
  6. elsif rest[0] >= element then
  7. # The first element of the rest is larger or equal than our element, so we want to insert it JUST before it.
  8. (sorted << element).concat(rest)
  9. else
  10. # The recursion.
  11. insert_into_sorted_helper(sorted << rest[0], element, rest[1..-1])
  12. end
  13.  
  14. end
  15.  
  16.  
  17. # Insert an element into a already sorted list. The resulting list stays sorted.
  18. def insert_into_sorted(sorted, element)
  19. insert_into_sorted_helper([],element,sorted)
  20. end
  21.  
  22.  
  23. def recursive_sort_helper(sorted, unsorted)
  24.  
  25. if unsorted.size == 0 then
  26. # Unsorted is 0, so everything is sorted
  27. sorted
  28. else
  29. first = unsorted[0]
  30. rest = unsorted[1..-1]
  31. # Insert the first element of the unsorted list into the already sorted list and do the recursion on the rest.
  32. recursive_sort_helper(insert_into_sorted(sorted, first), rest)
  33. end
  34. end
  35.  
  36.  
  37. # Sorts a list
  38. def recursive_sort(unsorted)
  39. # The empty list ([]) is already sorted, so we can use it as out sorted array
  40. recursive_sort_helper([],unsorted)
  41. end
  42.  
  43. unsorted = []
  44. while input = gets.chomp
  45. break if input.empty?
  46. unsorted << input.to_i # If you don't do to_i, your input will be saved as strings and the sort will behave differently.
  47. end
  48.  
  49.  
  50. puts recursive_sort(unsorted)
Add Comment
Please, Sign In to add comment