2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

HaskellのバブルソートをJavaScriptに直訳してみた

Last updated at Posted at 2014-11-02

Haskellで実装したバブルソートをJavaScriptに直訳してみました。効率は度外視して直訳を優先しています。

Haskell

bswap [x] = [x]
bswap (x:xs)
    | x > y     = y:x:ys
    | otherwise = x:y:ys
    where
        (y:ys) = bswap xs

bsort [] = []
bsort xs = y : bsort ys
    where
        (y:ys) = bswap xs

main = do
    print $ bswap [4, 3, 1, 5, 2]
    print $ bsort [4, 3, 1, 5, 2]
    print $ bsort [5, 4, 3, 2, 1]
    print $ bsort [4, 6, 9, 8, 3, 5, 1, 7, 2]
実行結果
[1,4,3,2,5]
[1,2,3,4,5]
[1,2,3,4,5]
[1,2,3,4,5,6,7,8,9]

JavaScript

"use strict";

function bswap(xs) {
    if (xs.length == 1) return xs;
    var x = xs.shift();
    var ys = bswap(xs);
    var y = ys.shift();
    if (x > y) return [y, x].concat(ys);
    return [x, y].concat(ys);
}

function bsort(xs) {
    if (xs.length == 0) return [];
    var ys = bswap(xs);
    var y = ys.shift();
    return [y].concat(bsort(ys));
}

console.log(bswap([4, 3, 1, 5, 2]));
console.log(bsort([4, 3, 1, 5, 2]));
console.log(bsort([5, 4, 3, 2, 1]));
console.log(bsort([4, 6, 9, 8, 3, 5, 1, 7, 2]));
実行結果
[ 1, 4, 3, 2, 5 ]
[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

varを付け忘れてバグに悩まされたので、敢えて"use strict"を残しています。

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?