Skip to content

Instantly share code, notes, and snippets.

@rttong
Last active December 15, 2015 21:48
Show Gist options
  • Save rttong/5327883 to your computer and use it in GitHub Desktop.
Save rttong/5327883 to your computer and use it in GitHub Desktop.
Chris Pine - Sorting an Array
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'])
@seanot
Copy link

seanot commented Apr 17, 2013

Thanks @SeanBr, your comment got me past a blind spot that has plagued me for the last few days.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment