Skip to content

Instantly share code, notes, and snippets.

@benolee
Created May 5, 2011 19:54
Show Gist options
  • Select an option

  • Save benolee/957777 to your computer and use it in GitHub Desktop.

Select an option

Save benolee/957777 to your computer and use it in GitHub Desktop.
def sort some_array # This "wraps" recursive_sort.
recursive_sort some_array, []
end
def recursive_sort unsorted_array, sorted_array
# Check to see if there is anything to sort
if unsorted_array.empty?
return sorted_array
else
# Start with the first member of unsorted array,
# just to have a starting point. We want to find the
# word that would come first if we cheated and used
# unsorted_array.sort
next_member = unsorted_array.first
# Loop through unsorted array, comparing values.
# Replace next_member with current value in the
# loop if it is less than next_member.
unsorted_array.each do |member|
if member < next_member
next_member = member # assign next_member to value of member
end
end
# At this point, next_member is the 'smallest' word
# in the unsorted_array. We need to remove it from
# unsorted_array and append it to the sorted_array.
# So, delete it from unsorted_array
unsorted_array.delete(next_member)
# Add it to the end of sorted_array
sorted_array.push(next_member)
# Call recursive_sort again, with the changed
# versions of unsorted_array and sorted_array
recursive_sort(unsorted_array, sorted_array)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment