LoginSignup
0
0

More than 5 years have passed since last update.

CoffeeScript でマージソート

Last updated at Posted at 2015-08-10
mergesort.coffee

# 配列をマージソート
mergeSort = (ary, isAsc = true)->
  tmpAry = ary.concat()

  split = (ary)->
    if ary.length < 2
      return ary
    mid = ary.length / 2 | 0
    a = split ary.slice 0, mid
    b = split ary.slice mid, ary.length
    merge ary, a, b
  merge = (ary, a, b)->
    unless b?
      return ary
    c = []
    aK = bK = cK = 0
    while aK < a.length and bK < b.length
      if isAsc ^ a[aK] > b[bK]
        c[cK] = a[aK]
        aK++
      else
        c[cK] = b[bK]
        bK++
      cK++
    c.concat (if a.length <= aK then b.slice bK else a.slice aK)
  split tmpAry
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0