1. Recursive implementation of merge sort:
#include <iostream>#include<vector>#include<string>#include<strstream>#include<algorithm>#include<unordered_map>using namespacestd;voidMergeSort (vector<int>& Nums, vector<int> ©,intStartintend) { if(Start = =end) {Copy[start]=Nums[start]; return; } intLen = (end-start)/2; MergeSort (nums, copy, start, start+Len); MergeSort (nums, copy, start+ len +1, end); inti = start, j = start + Len +1, index =start; while(I <= start + len && J <=end) { if(Nums[i] <Nums[j]) {Copy[index]=Nums[i]; I++; } Else{Copy[index]=Copy[j]; J++; } Index++; } while(I <= start + len)//Copy to the copy array if the first half of the paragraph has any remaining{Copy[index]=Nums[i]; ++i; ++index; } while(J <= End)//Copy to the copy array if the second half has the remainder{Copy[index]=Nums[j]; ++J; ++index; } for(inti = start;i <= end;i++)//The copy array is now in order, copying it into the original arrayNums[i] =copy[i];}intMain () {inta[8] = {8,4,7,0,3,5,9,1 }; Vector<int> Nums (A, A +8); intLen =nums.size (); Vector<int>copy (len); MergeSort (nums, copy,0, Len-1); for(auto e:nums) cout<< e <<" "; cout<<Endl; for(auto e:copy) cout<< e <<" "; cout<<Endl; return 0;}
2. Find the number of reverse pairs
Just a little modification of the merge sort algorithm
#include <iostream>#include<vector>#include<string>#include<strstream>#include<algorithm>#include<unordered_map>using namespacestd;intMergeSort (vector<int>& Nums, vector<int> ©,intStartintend) { if(Start = =end) {Copy[start]=Nums[start]; return 0; } intLen = (end-start)/2; intleft = MergeSort (nums, copy, start, start +Len); intright = MergeSort (nums, copy, start + len +1, end); inti = start, j = start + Len +1, index =start; intCNT =0; while(I <= start + len && J <=end) { if(Nums[i] <Nums[j]) {Copy[index]=Nums[i]; I++; } Else{Copy[index]=Copy[j]; J++; CNT+ = start + Len-i +1;//number of times statistics in reverse order} index++; } while(I <= start + len)//Copy to the copy array if the first half of the paragraph has any remaining{Copy[index]=Nums[i]; ++i; ++index; } while(J <= End)//Copy to the copy array if the second half has the remainder{Copy[index]=Nums[j]; ++J; ++index; } for(inti = start;i <= end;i++)//The copy array is now in order, copying it into the original arrayNums[i] =Copy[i]; returnLeft + right +CNT;}intMain () {inta[8] = {7,5,6,4 }; Vector<int> Nums (A, A +4); intLen =nums.size (); Vector<int>copy (len); cout<<"KKK"<<mergesort (nums, copy,0, Len-1) <<Endl; for(auto e:nums) cout<< e <<" "; cout<<Endl; for(auto e:copy) cout<< e <<" "; cout<<Endl; return 0;}
Merging sort C + + implementation and finding the number of reverse pairs