🙄
バブルソート
配列を昇順にする
step1. 関数を定義する。引数はarrとする
step2. n-1を使用したいので、nの配列の長さが必要になる
step3. nの長さを適当な変数に代入する
step4. 繰り返し処理で隣同士の数を比較する
step5. 比較して、その数が、隣接する数より大きければ順番を入れ替える
const nums = [1,5,8,2,4,9,10];
//step1
function bubbleSort(arr)
{
//step2,step3
const nl = nums.length;
//step4
for(let i = 0; i < nl -1; i++)
{
for(let j = 0; j < nl - 1 - i; j++)
{
//step5
if(arr[j] > arr[j+1])
{
[arr[j], arr[j+1]] = [arr[j+1], arr[j]];
}
}
}
return arr;
}
const new_nums = bubbleSort([...nums]);
console.log(new_nums);
Discussion