zoukankan      html  css  js  c++  java
  • 求数组的逆序对

    #include<iostream>
    #include<vector>
    using namespace std;
    
    void merge(vector<int>&input, int left, int right, int mid, vector<int>&temp,int &count){
        int i = left;
        int j = mid+1;
        int t = 0;//t=left也可以,因为最终都是要赋值给input[left]
        
        while (i<=mid&&j<=right){
            if (input[i] > input[j]){
                temp[t++] = input[j++];
                count += mid+1-i;//input[i]>input[j]时,左边比input[i]大的均与input[j]构成逆序对,总共mid+1-i
            }
            else{
                temp[t++] = input[i++];
            }
        }
        while (i <= mid){
            temp[t++] = input[i++];
        }
        while (j <= right){
            temp[t++] = input[j++];
        }
        t = 0;//t=left
        while (left <= right){
            input[left++] = temp[t++];
        }
        
    }
    
    void mergesort(vector<int>&input, int left, int right, vector<int>&temp,int &count){
        if (left < right){
            int mid = (left + right) / 2;
            mergesort(input, left, mid, temp,count);
            mergesort(input, mid + 1, right, temp,count);
            merge(input, left, right, mid, temp,count);
        }
    }
    int main(){
        vector<int>a = { 7,2,5,4};
        vector<int>b(a.size(), 0);
        
        int count = 0;
        mergesort(a, 0, a.size() - 1, b,count);
        for (int i = 0; i < a.size(); i++){
            cout << a[i] << endl;
        }
        
        cout << count << endl;
        system("pause");
        return 0;
    }
  • 相关阅读:
    docker架构的详解
    docker的核心原理-cgroup
    网络运维面试题
    100道linux运维笔试题
    运维岗位面试题集合
    python——筛子游戏
    同道前辈
    delphi中使用SocketStream读写数据的技巧
    百度地图API
    HTML中小meta的大作用
  • 原文地址:https://www.cnblogs.com/inception6-lxc/p/9073740.html
Copyright © 2011-2022 走看看