Skip to content

Instantly share code, notes, and snippets.

@dhirabayashi
Created April 12, 2020 02:20
Show Gist options
  • Select an option

  • Save dhirabayashi/8973b455e59f048d367f058d2f26154d to your computer and use it in GitHub Desktop.

Select an option

Save dhirabayashi/8973b455e59f048d367f058d2f26154d to your computer and use it in GitHub Desktop.
def compare_and_swap(x, up)
mid_point = x.size / 2
(0..(mid_point - 1)).each do |i|
if x[i] > x[mid_point + i] == up
x[i], x[mid_point + i] = x[mid_point + i], x[i]
end
end
end
def sub_sort(x, up)
if x.size == 1
return x
else
compare_and_swap(x, up)
mid_point = x.size / 2
first = sub_sort(x[0, mid_point], up)
second = sub_sort(x[mid_point, mid_point], up)
return first + second
end
end
def sort(x, up)
if x.size <= 1
return x
else
mid_point = x.size / 2
first = sort(x[0, mid_point], true)
second = sort(x[mid_point, mid_point], false)
x1 = first + second
return sub_sort(x1, up)
end
end
x = (0..7).to_a.shuffle
puts "sort前: #{x}"
x = sort(x, true)
puts "昇順ソート後: #{x}"
x = sort(x, false)
puts "降順ソート後: #{x}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment