バブルソート
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 38 39 40 41 42 43 44 45 |
function p(a){ console.log(a); } function swap(a, l, r){ var t = a[l]; a[l] = a[r]; a[r] = t; } function bubblesort(a){ for(var i=0; i<a.length-1; i++){ for(var j=i+1; j<a.length; j++){ if(a[j]<a[i]){ swap(a, i, j); } } } } function getRandomInt(min, max){ return min + Math.floor(Math.random() * (max-min+1)); } function setRandomForArray(a){ var min = 0; var max = 9; for(var i=0; i<a.length; i++){ a[i] = getRandomInt(min, max); } } function generateArray(size){ var a = []; for(var i=0; i<size; i++){ a[i] = 0; } return a; } function main(){ var size = 30; var a = generateArray(size); p(a); setRandomForArray(a); p(a); bubblesort(a); p(a); } main(); |
1 2 3 |
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] [ 7, 0, 7, 4, 0, 4, 9, 3, 2, 1, 9, 9, 3, 1, 1, 2, 5, 6, 3, 4, 3, 6, 5, 5, 7, 1, 4, 0, 1, 0 ] [ 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 7, 7, 7, 9, 9, 9 ] |