iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 23
0
Software Development

用JS來刷刷HackerRank系列 第 29

(30)HackerRank-Interview-Sorting-Sorting: Bubble Sort(javaScript ans)

題目
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]}`);

}
 
 

上一篇
(25)HackerRank-Interview-Arrays-Array Manipulation(javaScript ans)
系列文
用JS來刷刷HackerRank29
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言