Last active
December 15, 2015 21:48
-
-
Save rttong/5327883 to your computer and use it in GitHub Desktop.
Chris Pine - Sorting an Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sort arr #wrapper for rec_sort | |
rec_sort arr, [] #if you are trying to sort an array, you must pass an empty array as second parameter | |
end | |
def rec_sort unsorted, sorted | |
if unsorted.length <= 0 #if unsorted array length is less than or equal to zero | |
return sorted #return array sorted | |
end | |
#if we get here, it means there are still strings to sort | |
smallest = unsorted.pop #sets the variable "smallest" to equal the last element popped out from unsorted | |
still_unsorted = [] #creates new array to hold unsorted elements | |
unsorted.each do |tested_object| #do x for each of the elements inside unsorted | |
if tested_object < smallest #starting from 0, if unsorted element is less than current value for smallest | |
still_unsorted.push smallest #smallest is moved to the end of still_unsorted | |
smallest = tested_object #and tested_object is now set to equal smallest, because it was less than previous value for smallest | |
else | |
still_unsorted.push tested_object #if tested object is not less than smallest, the tested_object is moved to the end of still_unsorted | |
end | |
end | |
sorted.push smallest #puts the smallest element at the end of the sorted array | |
rec_sort still_unsorted, sorted #calls rec_sort method again | |
end | |
puts sort(['a', 'c', 'b', 'd']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So the idea is you pull an element from the unsorted array (pop pulls from the end, push adds to that same end). Then, taking that element you start to compare it to each of the originally unsorted elements left. If they are smaller, you say "well crap" and put your current smallest into still_unsorted and then proceed through the rest of the originally unsorted elements.
The result is you end up with the absolute smallest element as smallest and the rest of the array you orginally passed in as still_unsorted. You then say "ok, good, let's save this smallest element" and add it to the new sorted array (which was originally empty, but now has 1 element). So now you have still_unsorted and sorted, still_unsorted is 1 element shorter than before, and sorted is 1 element larger.
You call rec_sort to start all over, this time passing in your smaller still_unsorted and slightly less empty sorted.
This repeats until the unsorted array's length is 0. So every recursive step, you're taking 1 element(the smallest) from unsorted and adding it to sorted.