微软面试题:求一个序列的逆序对数

 

双层循环排序,时间为O(n2)

归并排序时间为O(nlog(n))

#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
int cnt=0;
void merge(vector<int> & nums,int left,int mid,int right);
void mergesort(vector<int> & nums,int start,int end);
int main(){
    int exa[8]={1, 7, 2, 9, 6, 4, 5, 3};
    vector<int> arr;
    for(int i=0;i<8;i++){
        arr.push_back(exa[i]);
    }
    mergesort(arr,0,arr.size()-1);
    printf("逆序对数为: %d\n",cnt);
    return 0;
}
void merge(vector<int> &nums,int left,int mid,int right){
    vector<int> temp;
    int l=left,r=right;
    while(l<=mid && r<=right){
        if(nums[l]>nums[r])
            {temp.push_back(nums[r++]);cnt+=mid-l+1;}
        else
            temp.push_back(nums[l++]);
    }
    while(l<=mid)
        temp.push_back(nums[l++]);
    while(r<=mid)
        temp.push_back(nums[r++]);
    for(int i=0;i<temp.size();i++)
        nums[left+i]=temp[i];
}
void mergesort(vector<int> &nums,int start,int end){
    if(start>=end) return;
    int mid=(end-start)/2+start;
    mergesort(nums,start,mid);
    mergesort(nums,mid+1,end);
    merge(nums,start,mid,end);
}

 

posted @ 2019-04-10 11:57  Joel_Wang  阅读(387)  评论(0编辑  收藏  举报