Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
7
Task/Sort-stability/Ruby/sort-stability-1.rb
Normal file
7
Task/Sort-stability/Ruby/sort-stability-1.rb
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
ary = [["UK", "London"],
|
||||
["US", "New York"],
|
||||
["US", "Birmingham"],
|
||||
["UK", "Birmingham"]]
|
||||
p ary.sort {|a,b| a[1] <=> b[1]}
|
||||
# MRI reverses the Birminghams:
|
||||
# => [["UK", "Birmingham"], ["US", "Birmingham"], ["UK", "London"], ["US", "New York"]]
|
||||
20
Task/Sort-stability/Ruby/sort-stability-2.rb
Normal file
20
Task/Sort-stability/Ruby/sort-stability-2.rb
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
class Array
|
||||
def stable_sort
|
||||
n = -1
|
||||
if block_given?
|
||||
collect {|x| n += 1; [x, n]
|
||||
}.sort! {|a, b|
|
||||
c = yield a[0], b[0]
|
||||
if c.nonzero? then c else a[1] <=> b[1] end
|
||||
}.collect! {|x| x[0]}
|
||||
else
|
||||
sort_by {|x| n += 1; [x, n]}
|
||||
end
|
||||
end
|
||||
|
||||
def stable_sort_by
|
||||
block_given? or return enum_for(:stable_sort_by)
|
||||
n = -1
|
||||
sort_by {|x| n += 1; [(yield x), n]}
|
||||
end
|
||||
end
|
||||
8
Task/Sort-stability/Ruby/sort-stability-3.rb
Normal file
8
Task/Sort-stability/Ruby/sort-stability-3.rb
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
ary = [["UK", "London"],
|
||||
["US", "New York"],
|
||||
["US", "Birmingham"],
|
||||
["UK", "Birmingham"]]
|
||||
p ary.stable_sort {|a, b| a[1] <=> b[1]}
|
||||
# => [["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]]
|
||||
p ary.stable_sort_by {|x| x[1]}
|
||||
# => [["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]]
|
||||
Loading…
Add table
Add a link
Reference in a new issue