Last active
September 30, 2021 16:48
-
-
Save Snarp/72d39d3312a832358d0255853da03514 to your computer and use it in GitHub Desktop.
Example Ruby implementations of stable_sort and stable_sort_by
This file contains hidden or 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
module Enumerable | |
# Sources: | |
# - https://stackoverflow.com/a/15442966/797772 | |
# - https://rubygems.org/gems/vex/versions/0.6.2 | |
def stable_sort_by | |
sort_by.with_index { |x,idx| [yield(x), idx] } | |
end | |
# def stable_sort_by | |
# i=0 | |
# sort_by { |x| [ yield(x), i+=1 ] } | |
# end | |
# Sources: | |
# - https://8thlight.com/blog/will-warner/2013/03/26/stable-sorting-in-ruby.html | |
# - http://moserei.de/2008/09/18/stable-array-sorting-in-ruby.html | |
# - https://web.archive.org/web/20081011045822/http://codesnippets.joyent.com/posts/show/19 | |
# Takes a block: | |
def stable_sort | |
n = 0 | |
c = lambda { |x| n+=1; [x, n] } | |
if block_given? | |
sort { |a, b| yield( c.call(a), c.call(b) ) } | |
else | |
sort_by &c | |
end | |
end | |
# # Doesn't take a block: | |
# def stable_sort | |
# n = 0 | |
# sort_by { |x| n+= 1; [x, n] } | |
# end | |
# | |
# def stable_sort | |
# sort_by.with_index { |x, idx| [x, idx] } | |
# end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment