Advertisement
unknown_0711

Untitled

Dec 13th, 2022
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1.  
  2. class Solution
  3. {
  4. static long inversionCount(long arr[], long n)
  5. {
  6. long temp[] = new long[(int)n];
  7. return _mergeSort(arr, temp, 0, n - 1);
  8. }
  9.  
  10. static long _mergeSort(long arr[], long temp[],
  11. long left, long right)
  12. {
  13. long mid, inv_count = 0;
  14. if (right > left) {
  15. mid = (right + left) / 2;
  16.  
  17. inv_count = _mergeSort(arr, temp, left, mid);
  18.  
  19. inv_count += _mergeSort(arr, temp, mid + 1, right);
  20.  
  21. inv_count += merge(arr, temp, left, mid + 1, right);
  22. }
  23. return inv_count;
  24. }
  25.  
  26. static long merge(long arr[], long temp[], long left,
  27. long mid, long right)
  28. {
  29. long i, j, k;
  30. long inv_count = 0;
  31. i = left;
  32. j = mid;
  33. k = left;
  34.  
  35. while ((i <= mid - 1) && (j <= right)) {
  36.  
  37. if (arr[(int)i] <= arr[(int)j]) {
  38. temp[(int)k++] = arr[(int)i++];
  39. }
  40. else {
  41. temp[(int)k++] = arr[(int)j++];
  42. inv_count = inv_count + (mid - i);
  43. }
  44. }
  45.  
  46. while (i <= mid - 1)
  47. temp[(int)k++] = arr[(int)i++];
  48.  
  49. while (j <= right)
  50. temp[(int)k++] = arr[(int)j++];
  51.  
  52. for (i = left; i <= right; i++)
  53. arr[(int)i] = temp[(int)i];
  54.  
  55. return inv_count;
  56. }
  57.  
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement