Created
April 12, 2020 02:20
-
-
Save dhirabayashi/8973b455e59f048d367f058d2f26154d to your computer and use it in GitHub Desktop.
https://github.com/ghmagazine/rustbook/blob/master/ch03/bitonic-sorter/py-src/bitonic_sorter.py をRubyで書き直してみた
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
| 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