归并排序(JS)

归并排序(从小到大)

算法复杂度:
最好情况:O(nlogn)
最坏情况:O(nlogn)
平均情况:O(nlogn)
空间复杂度:O(n)
稳定性:稳定

function mergeSort(arr, start, end) {
    if (start >= end) {
        return;
    }
    let mid = start + parseInt((end - start) / 2);
    mergeSort(arr, start, mid);
    mergeSort(arr, mid + 1, end);
    merge(arr, start, mid, end);
}

function merge(arr, start, mid, end) {
    let temp = [];
    let len = 0;
    let i = start, j = mid + 1;
    for (; i <= mid && j <= end;) {
        if (arr[i] > arr[j]) {
            temp[len++] = arr[j++];
        } else {
            temp[len++] = arr[i++];
        }
    }
    while (i <= mid) {
        temp[len++] = arr[i++];
    }
    while (j <= end) {
        temp[len++] = arr[j++];
    }
    for (let t = 0; t < len; t++) {
        arr[t + start] = temp[t];
    }
}

let arr = [3,2,1,5,4];

mergeSort(arr , 0 , 4);

归并排序求逆序对

let num = 0; // 逆序对的个数

function mergeSort(arr, start, end) {
    if (start >= end) {
        return;
    }
    let mid = start + parseInt((end - start) / 2);
    mergeSort(arr, start, mid);
    mergeSort(arr, mid + 1, end);
    merge(arr, start, mid, end);
}

function merge(arr, start, mid, end) {
    let temp = [];
    let len = 0;
    let i = start, j = mid + 1; 
    for (; i <= mid && j <= end;) {
        if (arr[i] > arr[j]) {
          num += mid - i + 1;   // ============> core code ,
                                // 如果arr[i] > arr[j] , 则i~mid之间(包括i和mid)的元素都与j是逆序对 
          temp[len++] = arr[j++];
        } else {
          temp[len++] = arr[i++];
        }
    }
    while (i <= mid) {
        temp[len++] = arr[i++];
    }
    while (j <= end) {
        temp[len++] = arr[j++];
    }
    for (let t = 0; t < len; t++) {
        arr[t + start] = temp[t];
    }
}

let arr = [1,2,3,4,5,6,7,0];

mergeSort(arr , 0 , 7);

例题:
每日一题——最小的K个数(归并排序)
每日一题——数组中的逆序对(归并排序)

你可能感兴趣的:(算法)