Advertisement
unknown_0711

Untitled

Oct 12th, 2022
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. class Solution
  2. {
  3. // arr[]: Input Array
  4. // N : Size of the Array arr[]
  5. //Function to count inversions in the array.
  6. static long inversionCount(long arr[], long n)
  7. {
  8. long p = conqur (arr, 0, n - 1, n);
  9. return p;
  10. }
  11. // static long devide(long a[],long l,long r){
  12. // long p=0;
  13. // if(l<=r){
  14. // long mid=l+(r-l)/2;
  15. // p+=devide(a,l,mid);
  16. // p+= devide(a,mid+1,r);
  17. // p+= conqur(a,l,mid,r);
  18. // }
  19. // return p;
  20. // }
  21. static long conqur(long a[], long l, long r, long n)
  22. {
  23.  
  24. long mid = (l + r) / 2;
  25. long ans = 0;
  26. long indx1 = l, indx2 = mid + 1;
  27. if (l < r)
  28. {
  29. long []aa= new long[(int)(r-l+1)];
  30. ans += conqur(a, l, mid, n);
  31. ans += conqur(a, mid + 1 , r, n);
  32. long x=0;
  33. while (indx1 <= mid && indx2 <= r) {
  34. if (a[(int)indx1] <= a[(int)indx2]) {
  35.  
  36. aa[(int)x++] = a[(int)indx1++];
  37. } else {
  38. ans += mid - indx1 + 1;
  39. aa[(int)x++] = a[(int)indx2++];
  40.  
  41. }
  42. }
  43. while (indx1 <= mid) {
  44. aa[(int)x++] = a[(int)indx1++];
  45. }
  46. while (indx2 <= r) {
  47. aa[(int)x++] = a[(int)indx2++];
  48. }
  49. x=0;
  50. for(long i=l;i<=r;i++){
  51. a[(int)i]=aa[(int)x++];
  52. }
  53.  
  54. }
  55. return ans;
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement