前端面试中常被问到的各类排序,看似是没什么作用,但其实能够清晰的看出面试者的基础水平如何。 同时了解这些基础的东西更有助于我们的编程思维。
快排
const quickSort = (arr = []) => {
if (arr.length < 2) return arr;
const left = [];
const right = [];
const pivotIndex = Math.floor(arr.length / 2);
const pivot = arr.splice(pivotIndex, 1)[0];
for (let i = 0; i < arr.length; i++) {
if (arr[i] < pivot) left.push(arr[i]);
else right.push(arr[i])
}
return quickSort(left).concat([pivot], quickSort(right))
}
冒泡排序
const bubbleSort=(arr=[])=>{
if(arr.length<2) return arr;
const len=arr.length;
for(let i=0;i<len-1;i++){
for(let j=0;j<len-1-i;j++){
if(arr[j]>arr[j+1]){
const temp=arr[j];
arr[j]=arr[j+1]
arr[j+1]=temp
}
}
}
return arr;
}