使用 JavaScript 使用氣泡排序對陣列排序


我們需要編寫一個 JavaScript 函式,該函式接收一個字面量陣列,並使用氣泡排序對它進行排序。

示例

程式碼如下 −

const arr = [4, 56, 4, 23, 8, 4, 23, 2, 7, 8, 8, 45];
const swap = (items, firstIndex, secondIndex) => {
   var temp = items[firstIndex];
   items[firstIndex] = items[secondIndex];
   items[secondIndex] = temp;
};
const bubbleSort = items => {
   var len = items.length,
   i, j;
   for (i=len-1; i >= 0; i--){
      for (j=len-i; j >= 0; j--){
         if (items[j] < items[j-1]){
            swap(items, j, j-1);
         }
      }
   }
   return items;
};
console.log(bubbleSort(arr));

輸出

控制檯輸出 −

[
   2, 4, 4, 4, 7,
   8, 8, 8, 23, 23,
   45, 56
]

更新於: 2020-10-15

299 人瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告