求逆序对函数(简单方便)

int mergeSort(vector<int>& nums, int left, int right) {
    if (left >= right) return 0;
 
    int mid = left + (right - left) / 2;
 
    // 分治递归
    long long count = mergeSort(nums, left, mid) + mergeSort(nums, mid + 1, right);
 
    // 归并合并
    vector<int> temp(right - left + 1);
    int i = left, j = mid + 1, k = 0;
 
    while (i <= mid && j <= right) {
        if (nums[i] <= nums[j])
            temp[k++] = nums[i++];
        else {
            temp[k++] = nums[j++];
            count += mid - i + 1;  // 统计逆序对数量
        }
    }
 
    while (i <= mid)
        temp[k++] = nums[i++];
    while (j <= right)
        temp[k++] = nums[j++];
 
    for (int p = 0; p < k; ++p)
        nums[left + p] = temp[p];
 
    return count;
}
posted @ 2024-01-05 00:00  yufan1102  阅读(2)  评论(0编辑  收藏  举报