java - Number of inversions in array -


i trying find out number of inversion in array. have applied mergesort. , when merging sub arrays counted number if value of right subarray less value of left sub array. code not work if array contains lot of data.

private static long getnumberofinversions(int[] a, int[] b, int left,                 int right) {     long numberofinversions = 0;     if (right > left)     {         int ave = (left + right) / 2;         numberofinversions = getnumberofinversions(a, b, left, ave);         numberofinversions += getnumberofinversions(a, b, ave + 1, right);         numberofinversions += merge(a, b, left, ave + 1, right);     }     return numberofinversions; }  public static long merge(int[] a, int b[], int left, int ave, int rigth) {     int = 0, j = left, k = ave;     long count = 0;     while (j <= ave - 1 && k <= rigth)     {         if (a[j] <= a[k])         {             b[i] = a[j];             i++;             j++;         }         else         {             b[i] = a[k];             count += ave - j;             i++;             k++;         }     }     while (j <= ave - 1)     {         b[i] = a[j];         i++;         j++;      }     while (k <= rigth)     {         b[i] = a[k];         i++;         k++;     }     while (left <= rigth)     {         a[left] = b[i];         left++;         i++;     }     return count; }  public static void main(string[] args) {     scanner scanner = new scanner(system.in);     int n = scanner.nextint();     int[] = new int[n];     (int = 0; < n; i++)     {         a[i] = scanner.nextint();     }     int[] b = new int[n];     system.out.println(getnumberofinversions(a, b, 0, n - 1)); } 


Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -