冒泡排序
javascript
function bubbleSort(arr) {
for(let i = 0; i < arr.length; i++) {
for(let j = 1; j < arr.length - 1 - i; j ++) {
if(arr[j - 1] > arr[j]) {
const temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
}
}
}
bubbleSort([5,4,3,2,1])
选择排序
javascript
function selectSort(arr) {
let minIndex = 0
for(let i = 0; i < arr.length; i++) {
minIndex = i;
for(let j = i; j < arr.length - 1; j ++) {
if(arr[j] > arr[j+1]) {
minIndex = j+1;
}
}
if(minIndex !== i) {
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]]
}
}
}
selectSort([5,4,3,2,1])
插入排序
javascript
function insertSort(arr) {
const len = arr.length;
for(let i = 1; i < len; i ++) {
if(arr[i - 1] > arr[i]) {
const temp = arr[i];
let j = i;
while(j > 0 && temp < arr[j - 1]) {
arr[j] = arr[j-1];
j--;
}
arr[j] = temp;
}
}
console.log(arr)
}
insertSort([5,4,3,2,1])
归并排序
递归
javascript
function mergeSort(arr) {
const len = arr.length;
if(len <= 1) {
return arr;
}
const mid = Math.floor(len / 2);
const leftArr = mergeSort(arr.slice(0, mid))
const rightArr = mergeSort(arr.slice(mid, len));
const res = mergeArr(leftArr, rightArr);
console.log(res)
return res;
}
function mergeArr(left, right) {
const leftLen = left.length;
const rightLen = right.length;
let l = 0;
let r = 0;
let res = [];
while(l < leftLen && r < rightLen) {
if(left[l] < right[r]) {
res.push(left[l]);
l++;
} else {
res.push(right[r]);
r++;
}
}
if(l < leftLen) {
res = res.concat(left.slice(l))
} else {
res = res.concat(right.slice(r))
}
return res
}
mergeSort([5,4,3,2,1])