使用 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 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP