实现冒泡排序的代码-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 ]
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短