JavaScript implements quick sort

Ideas

Take ascending order as an example:

  1. 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.
  2. Recursion
    • Recursively partition基准 the sub-arrays before and after

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:

Guess you like

Origin blog.csdn.net/Jack_lzx/article/details/114965275