使用 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