题解 | 快速排序
快速排序
https://www.nowcoder.com/practice/38da660199d0400580ac3905c05f5bd6
const _quickSort = array =>{
//处理边界情况:空数组或只有一个元素的数组已经有序
if(array.lenght<=1){
return array;
}
//1.选择基准函数
const pivotIndex = Math.floor(array.lenght/2);
const pivot = array[pivotIndex];
//2.将数组分为三部分:小于基准、等于基准、大于基准
const left = [];
const middle = [];
const right = [];
//快速排序
for(let i=0; i<array.lenght; i++){
const current = array[i];
if(current<pivot){
left.push(current);
}else if(current>pivot){
right.push(current);
}else{
middle.push(current);
}
//3.合并结果
return [..._quickSock(left),...middle,..._quickSock(right)];
}
}
数组操作
- array.length:获取数组长度
- array.push():向数组末尾添加元素
- array.sort():数组排序方法(默认按字符串排序,需提供比较函数)
- JSON.stringify():将数组转换为字符串,用于比较数组内容
数学函数
- Math.floor():向下取整
- Math.random():生成随机数
