題目
Sorting: Bubble Sort
舉例輸入
3
1 2 3
舉例輸出
Array is sorted in 0 swaps.
First Element: 1
Last Element: 3
舉例輸入
3
3 2 1
舉例輸出
Array is sorted in 3 swaps.
First Element: 1
Last Element: 3
解析
題旨要好好地寫排序,且用氣泡排序
氣泡排序是排序方法中最簡單,但效能最差的
但偏偏面試又很愛在白板考這題
輸出有三排了幾次
第一個數為何
最後的數為何
如果不是因為排了幾次,其實.sort()就可以搞定了
function countSwaps(a) {
let swaps = 0;
for (let i = 0; i < a.length; i++) {
let iterSwaps = 0;
for (let j = 0; j < a.length - 1; j++) {
if (a[j] > a[j + 1]) {
// do a swap
[a[j], a[j + 1]] = [a[j + 1], a[j]];
iterSwaps++;
}
}
if (iterSwaps == 0) {
// it's sorted!
break;
} else {
// not quite yet, add up
swaps += iterSwaps;
}
}
console.log(`Array is sorted in ${swaps} swaps.`);
console.log(`First Element: ${a[0]}`);
console.log(`Last Element: ${a[a.length - 1]}`);
}