, Strict Weak Ordering.
, ( x < y y < z, x < z). :
, m < n, , n < < . .
, . -, , , , O (n ^ 2), .
, before?.
require 'yaml'
hash = YAML.load '
a:
after:
before:
l:
after:
before:
n:
after:
before: l
b:
after:
before:
m:
after:
before:
c:
after:
before:
z:
after:
before:
'
hash.each do |k,v|
v.each do |vk,vv|
v[vk] = (vv||'').split
end
end
class Hash
def without *ks
delete_if { |k,v| ks.include? k }
end
def delete! *ks
replace without *ks
end
end
def print_keys hash
puts hash.map(&:first).join(' ')
end
def sort hash
array = hash.to_a
selection_sort array
print_keys array
Hash[array]
end
def selection_sort array
(0...array.length).each do |i|
min = i
((i+1)...array.length).each do |j|
min = j if before?(array[j], array[min])
end
temp = array[min]
array[min] = array[i]
array[i] = temp
end
end
def before? a, b
b.last['after'].include?(a.first) || a.last['before'].include?(b.first)
end
def test hash
puts nil,nil
print_keys hash
puts '-'*hash.count*3
hash.count.times { hash = sort hash }
end
test hash
:
$ ruby sort_test.rb
a l n b m c z
---------------------
a n l b m c z
a n l b m c z
a n l b m c z
a n l b m c z
a n l b m c z
a n l b m c z
a n l b m c z