排序之后数组中元素的大小依次递增
- 冒泡排序
const bubbleSort = arr => {
const len = arr.length;
if (len < 2) return arr;
for (let i = 0; i < len; i++) {
for (let j = 0; j < i; j++) {
if (arr[j] > arr[i]) {
const temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
return arr;
}
2.插入排序
const insertSort = arr => {
const len = arr.length;
let current;
for (let i = 1; i < len; i++) {
current = arr[i];
while (i - 1 >= 0 && arr[i - 1] > current) {
arr[i] = arr[i - 1];
i--;
}
arr[i] = current;
}
return arr;
}
- 快速排序
const quickSort = arr => {
if (arr.length < 2) return arr
const index = Math.floor(arr.length / 2)
const pivot = arr.splice(index, 1)[0]
const left = []
const right = []
for (let i = 0; i < arr.length ; i++) {
if (arr[i] < pivot) {
left.push(arr[i])
} else if (arr[i] >= pivot) right.push(arr[i])
}
return quickSort(left).concat([pivot], quickSort(right))
}