Ideas
Take ascending order as an example:
- Partition
- Choose an element from the array as you want
基准
, all基准
smaller elements are placed in the基准
front, and larger基准
elements are placed in the基准
back.
- Choose an element from the array as you want
- Recursion
- Recursively partition
基准
the sub-arrays before and after
- Recursively partition
The ascending order quick sort animation demonstration is shown in the figure:
Time complexity : O(nlogN)
achieve
Existing array [7, 5, 4, 15, 3, 9, 6, 12]
, sort in ascending order:
Array.prototype.quickSort = function() {
const rec = arr => {
if (arr.length <= 1) {
return arr; }
const left = [];
const right = [];
// 选择基准为数组第一个元素
const mid = arr[0];
// 从第二个元素开始遍历数组
for (let i = 1; i < arr.length; i++) {
if (arr[i] < mid) {
// 比基准小,放到左数组
left.push(arr[i]);
} else {
// 比基准大,放到右数组
right.push(arr[i]);
}
}
// 返回连接好的数组
return [...rec(left), mid, ...rec(right)];
};
const res = rec(this);
// 将res拷贝到this
res.forEach((item, index) => {
this[index] = item;
});
};
const arr = [7, 5, 4, 15, 3, 9, 6, 12];
arr.quickSort();
console.log(arr);
Results of the: