含义:自己调自己
递归三要素:定义函数、终止条件和等价关系式
小案例:排序
let arr1 = [8, 8, 9, 13, 45, 8, 0, 1, 9, 66];
//定义函数
function quickSort(arr) {
//终止条件
if (arr.length <= 1) return arr;
const baseIndex = Math.floor(arr.length / 2);
console.log(baseIndex);
const baseVal = arr.splice(baseIndex, 1)[0];
console.log(baseVal);
const left = [];
const right = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] < baseVal) {
left.push(arr[i]);
} else {
right.push(arr[i])
}
}
//等价关系式
return quickSort(left).concat(baseVal, quickSort(right));
}
console.log(quickSort(arr1));