Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ソートと計算量のはなし_in_JavaScript.pdf

okym
May 26, 2022
830

 ソートと計算量のはなし_in_JavaScript.pdf

okym

May 26, 2022
Tweet

Transcript

  1. こうなる $ time node sort.js 計算量 時間 1000 x 1000

    x 1000 10^9 0.721 s 10000 x 1000 x 1000 10^10 8.760 s 10000 x 10000 x 1000 10^11 106.3 s 10000 x 10000 x 10000 10^12 1396 s
  2. ソートの仕様 ECMAScript2021 Language Specification より引用 > The elements of this

    array are sorted. The sort must be stable (that is, elements that compare equal must remain in their original order). If comparefn is not undefined, it should be a function that accepts two arguments x and y and returns a negative value if x < y, zero if x = y, or a positive value if x > y. ・stable sort (※1)でなければならない (※2) ・比較関数は2つの引数を受け取って x<yなら負、x=yなら0、x>yなら正を返す ※1 同等なデータのソート前の順序がソート後も保存されるもの ※2 ES2019以降の仕様。ES2015の仕様だとstableとは限らない。ただし V8(v7.0以降)のソートアルゴリズムは stableなので実装はstable。
  3. ソートの仕様 ECMAScript2021 Language Specification より引用 > The elements of this

    array are sorted. The sort must be stable (that is, elements that compare equal must remain in their original order). If comparefn is not undefined, it should be a function that accepts two arguments x and y and returns a negative value if x < y, zero if x = y, or a positive value if x > y. ・stable sort (※1)でなければならない (※2) ・比較関数は2つの引数を受け取って x<yなら負、x=yなら0、x>yなら正を返す ※1 同等なデータのソート前の順序がソート後も保存されるもの ※2 ES2019以降の仕様。ES2015の仕様だとstableとは限らない。ただし V8(v7.0以降)のソートアルゴリズムは stableなので実装はstable。 ・アルゴリズムの指定はない ・JSエンジンが異なれば異なるソート アルゴリズムが使われる
  4. JSエンジンとソート実装 - V8(Chrome、Node.js) - v6以前:配列の要素数が10以下では挿入ソート、それ以上はクイックソート - v7以降:ティムソート - Chakra(IE、旧Edge) -

    配列の要素数が512個より大きい場合はクイックソート、それ以下なら二分挿入ソート - SpiderMonkey(Firefox) - マージソート - JavaScriptCore(Safari) - 以前は選択ソート、いまはマージソート 参考:https://memolog.org/2018/about-array-prototype-sort.html
  5. 今回扱うソート - バブルソート - 選択ソート - 挿入ソート - マージソート -

    クイックソート https://git01.mdomain/takehiko.okayama/js-array-sort
  6. 選択ソート 未整列データの中の最小値を探し、先頭 と入れ替える。最小値を整列済みデータ とする。ソートが完了するまでこれを繰り 返す。 - 平均計算量 O(n^2) - 最悪計算量

    O(n^2) - not stable ※ ※ →の実装のように「minとi番目を入 れ替える」とnot stable、「minとi番目の前 に挿入して他を前にずらす」とstable https://medium-company.com/%e9%81%b8%e6%8a%9e% e3%82%bd%e3%83%bc%e3%83%88/
  7. JSエンジンとソート実装 - V8(Chrome、Node.js) - v6以前:配列の要素数が10以下では挿入ソート、それ以上はクイックソート - v7以降:ティムソート - Chakra(IE、旧Edge) -

    配列の要素数が512個以下では場合は二分挿入ソート、それ以上はクイックソート - SpiderMonkey(Firefox) - マージソート - JavaScriptCore(Safari) - 以前は選択ソート、いまはマージソート 参考:https://memolog.org/2018/about-array-prototype-sort.html