标签:面试 push clu size code iostream 循环 class include
双层循环排序,时间为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); }
标签:面试 push clu size code iostream 循环 class include
原文地址:https://www.cnblogs.com/joelwang/p/10682604.html