不论在工作中还是面试,或多或少都会用到/问到排序的一些方法,多了解一点总是不亏的
冒泡排序
let nums = [8, 2, 6, 5, 4, 1, 3];
function sort(nums = []) {
for(let i = 0; i< nums.length; i++) {
for(let j = 0; j< nums.length -1 - i; j++) {
if(nums[j] > nums[j + 1]) {
[nums[j],nums[j + 1]] = [nums[j + 1], nums[j]]
}
}
}
return nums;
}
const sortSize = sort(nums);
console.log(sortSize); // [ 1, 2, 3, 4, 5, 6, 8]
选择排序
let nums = [8, 2, 6, 5, 4, 1, 3];
function sort(nums) {
let index = 0;
for (let i = 0; i < nums.length - 1; i++) {
index = i;
for (let j = i + 1; j < nums.length; j++) {
if (nums[j] < nums[index]) {
index = j;
}
}
if (index !== i) {
[nums[i], nums[index]] = [nums[index], nums[i]];
}
}
return nums;
}
const sortSize = sort(nums);
console.log(sortSize); // [ 1, 2, 3, 4, 5, 6, 8]
插入排序
let nums = [8, 2, 6, 5, 4, 1, 3];
function sort(nums) {
for (let i = 1; i < nums.length; i++) {
let j = i;
let target = nums[j];
while (j > 0 && nums[j - 1] > target) {
nums[j] = nums[j - 1];
j--;
}
nums[j] = target;
}
return nums;
}
const sortSize = sort(nums);
console.log(sortSize); // [ 1, 2, 3, 4, 5, 6, 8]
快速排序
let nums = [8, 2, 6, 5, 4, 1, 3];
function sort(arr) {
if(arr.length < 2) {
return arr;
} else {
const pivot = arr[0]; // 基准值
const pivotArr = []; // 一样大的放中间
const lowArr= []; // 小的放左边
const hightArr = []; // 大的放右边
arr.forEach(current => {
if(current === pivot) pivotArr.push(current);
else if(current > pivot) hightArr.push(current);
else lowArr.push(current);
})
return sort(lowArr).concat(pivotArr).concat(sort(hightArr));
}
}
const sortSize = sort(nums);
console.log(sortSize); // [ 1, 2, 3, 4, 5, 6, 8]
往期文章