插入排序
const insertSort = (list) => {
if (list.length <= 1) return list
for (let i = 1; i < list.length; i++) {
const pivot = list[i]
let j = i - 1
while (j >= 0 && list[j] > pivot) {
list[j + 1] = list[j]
j--
}
list[j + 1] = pivot
}
return list
}
insertSort([1,7,2,6,5,4,3,9,0,8])
冒泡排序
const bubbleSort = (list) => {
if (list.length <= 1) return list
for (let i = list.length - 1; i > 0; i--) {
for (let j = 0; j < i; j++) {
if (list[j] > list[j + 1]) {
const temp = list[j + 1]
list[j + 1] = list[j]
list[j] = temp
}
}
}
return list
}
bubbleSort([1,7,2,6,5,4,3,9,0,8])
快速排序
const quickSort = (list) => {
if (list.length <= 1) return list
const left = []
const right = []
const pivot = list.at(-1)
for (let i = 0; i < list.length - 1; i++) {
if (list[i] < pivot) {
left.push(list[i])
}
if (list[i] > pivot) {
right.push(list[i])
}
}
return [].concat(quickSort(left), [pivot], quickSort(right))
}
quickSort([1,7,2,6,5,4,3,9,0,8])