冒泡排序
每次比较两个相邻的元素,如果它们的顺序错误,就交换过来。
function sort(arr = []) {
const { length } = arr;
for (let i = 0; i < length - 1; i++) {
for (let j = 0; j < length - 1 - i; j++) {
if (arr[j] < arr[j + 1]) {
const temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
console.log(arr);
}
const arr = [5, 3, 5, 2, 8];
sort(arr); // [8, 5, 5, 3, 2]
改动下,按分数排名打印出名字:
function sort(arr = []) {
const { length } = arr;
for (let i = 0; i < length - 1; i++) {
for (let j = 0; j < length - 1 - i; j++) {
if (arr[j].score < arr[j + 1].score) {
const temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// console.log(arr);
for (let i = 0; i < length; i++) {
console.log(arr[i].name);
}
}
const arr = [
{
name: 'A',
score: 5,
},
{
name: 'B',
score: 8,
},
{
name: 'C',
score: 5,
},
{
name: 'D',
score: 3,
},
{
name: 'E',
score: 2,
},
];
sort(arr); // B A C D E
缺点:
- 复杂度高,O(N*N)