快速排序

快速排序.jpg

function QSort(arr, low, high) {
    if (low < high) {
        let pivot = Partition(arr, low, high);
        QSort(arr, low, pivot - 1);
        QSort(arr, pivot + 1, high);
    }

    function Partition(arr, low, high) {
        let temp = arr[low];
        while (low < high) {
            while (low < high && arr[high] >= temp) {
                high--;
            }
            arr[low] = arr[high];
            while (low < high && arr[low] <= temp) {
                low++;
            }
            arr[high] = arr[low];
        }
        arr[low] = temp;
        return low;
    }
}

let arr = [-1, -3, -2, -5, -6, 18, 12, 14, -4];
QSort(arr, 0, arr.length - 1);
console.log(arr);

归并排序

归并排序.gif

/**
 * 归并排序
 * @param {*} nums 要排序的数组
 * @returns 要排序的数组
 */
let sortArray = function (nums) {
    /**
     * 归并排序的主体处理函数
     * @param {*} temp 状态暂存数组
     * @param {*} arr 排序的数组
     * @param {*} l 左坐标
     * @param {*} r 右坐标
     */
    function mergeSort(temp, arr, l, r) {
        if (l >= r) return;
        let mid = ((r - l) >> 1) + l;
        mergeSort(temp, arr, l, mid);
        mergeSort(temp, arr, mid + 1, r);
        for (let i = l; i <= r; i++) {
            temp[i] = arr[i];
        }
        for (let curr = l, i1 = l, i2 = mid + 1; curr <= r; curr++) {
            if (i1 == mid + 1 || temp[i2] < temp[i1]) {
                arr[curr] = temp[i2++];
            } else if (i2 == r + 1 || temp[i1] <= temp[i2]) {
                arr[curr] = temp[i1++];
            }
        }
    }
    mergeSort([], nums, 0, nums.length - 1);
    return nums;
};

let arr = [1, 11, 15, 12, -8, 0, -90, 100, 0];
sortArray(arr);
console.log(arr);
/* [ -90, -8, 0, 0, 1, 11, 12, 15, 100] */