Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def sort(arr)
- rec_sort(arr, [])
- end
- #define a sort method that takes an array as a parameter
- #inside the sort method, have it call a recursive sort method that takes
- # two parameters to be defined later
- def rec_sort(unsorted, sorted)
- if unsorted.length <= 0
- return sorted
- end
- #rec_sort method takes an unsorted array and a sorted array
- #checks to see if the unsorted array is equal to or less than 0
- #essentially checking if it is empty
- #if it is empty, then just return the sorted array
- #if it is not empty, there is more work to be done
- smallest = unsorted.pop
- still_unsorted = []
- #sets a variable smallest equal to the last element of the unsorted array
- #also removes that element from the unsorted array
- #initializes an empty array called still_unsorted
- unsorted.each do |tested_object|
- if tested_object < smallest
- still_unsorted.push(smallest)
- smallest = tested_object
- else
- still_unsorted.push(tested_object)
- end
- end
- #after we've established that the unsorted array is not empty, we are going to iterate through it to add words to the sorted array
- #going through the unsorted array, we call each element tested_object
- #if tested_object is less than (lexigcoraphically) smallest, we push smallest to the still_unsorted array, and we make smallest equal to tested_object
- #if tested_object > smallest, then we push tested_object into the still_unsorted array
- #this is creating the still_unsorted array
- #now 'smallest' really does point to the smallest element that 'unsorted' contained, and all the rest of it is in still_unsorted
- sorted.push(smallest)
- #push smallest into the sorted array
- rec_sort(still_unsorted, sorted)
- end
- puts(sort(['can', 'feel', 'singing', 'like', 'a', 'can']))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement