ここでは、当社の新人研修受講者に向けて、JavaScriptのサンプルコードを紹介しています。
バブルソートのサンプルコード
ファイルを読み込むとランダムな数列を表示します。「bubbleSort」ボタンを押すと数列を昇順に整列します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<!DOCTYPE html> <html> <head> <title>bubble sort</title> <meta charset="UTF-8"> <script> Array.prototype.bubble = function () { for (var i = this.length - 1; i > 0; i--) { for (var j = 0; j < i; j++) { if (this[j] > this[j + 1]) { var temp = this[j]; this[j] = this[j + 1]; this[j + 1] = temp; } } } return this; }; var cards = [4, 6, 2, 1, 8, 9, 6, 5, 7, 3]; function init() { document.getElementById("result").textContent = cards.join(","); } function bubble() { cards.bubble(); document.getElementById("result").textContent = cards.join(","); } </script> </head> <body onload="init()"> <button onclick = "bubble()">bubbleSort</button> <p id = "result"></p> </body> </html> |