fork download
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. int helpInverse(int A[],int start,int mid,int end){
  6.  
  7. int len=end-start+1;
  8.  
  9. vector<int>temp(len+1);
  10. int i=start,j=mid+1;
  11. int cnt=0,x=0;
  12. while(i<=mid && j<=end){
  13.  
  14. if(A[i]<=A[j]){
  15. temp[x++]=A[i++];
  16. }else{
  17. temp[x++]=A[j++];
  18. cnt+=(mid-i)+1;
  19. }
  20.  
  21. }
  22.  
  23. while(i<=mid){
  24. temp[x++]=A[i++];
  25. }
  26.  
  27. while(j<=end){
  28. temp[x++]=A[j++];
  29. }
  30.  
  31. int t=start;
  32. for(int i=0;i<x;++i){
  33. A[t++]=temp[i];
  34. }
  35.  
  36. return cnt;
  37. }
  38.  
  39. int countInversions(int A[],int start,int end){
  40. int x=0;
  41. if(start<end){
  42.  
  43. int mid=(start+end)/2;
  44.  
  45. x+=countInversions(A,start,mid);
  46. x+=countInversions(A,mid+1,end);
  47. x+=helpInverse(A,start,mid,end);
  48. }
  49. return x;
  50. }
  51.  
  52.  
  53. int main() {
  54. // your code
  55. int arr[5]={1, 20, 6, 4, 5};
  56. cout<<"ans: "<<countInversions(arr,0,4)<<endl;
  57.  
  58. return 0;
  59. }
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
ans: 5