rubyでクイックソート
def quick(a) return a if a.length <= 1 left = [] right = [] p = 0 p_s = [] a.each_with_index do |v,i| next if i == 0 if v > a[p] right.push(v) elsif v < a[p] left.push(v) else p_s.push(v) end end p_s.push(a[p]) quick(left) + p_s + quick(right) end end def test_quick assert_equal([1,5,8],@o.quick([8,1,5])) assert_equal([2,3,3],@o.quick([3,2,3])) assert_equal([3,3,3],@o.quick([3,3,3])) assert_equal([1,2,3,4,5,6,7,8,9], @o.quick([9,5,1,8,3,2,6,7,4])) end $ ruby test.rb Loaded suite test Started ...... Finished in 0.018943959 seconds. --------------------------------------------------- 6 tests, 23 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications 100% passed --------------------------------------------------- 316.72 tests/s, 1214.11 assertions/s
- 参考
https://www.codereading.com/algo_and_ds/algo/quick_sort.html
考えたけどわからなくて、ほぼ参考サイトの答え丸写し。でもある程度考えて分からなかったのだから、答えみても仕方ない。コードが動いたので良かった。すっきりした。