Change it on the basis of merge sort.
1 Public classInversions {2 3 Public Static intInversions (int[] A,intPintR)4 { 5 6 if(p<R)7 {8 intQ = (int) Math.floor ((p+r)/2 );9 intleft =inversions (a,p,q);Ten intright = inversions (a,q+1, R); One intc =combine (a,p,q,r); A returnLeft + right +C; - } - return0; the - } - Public Static intCombineint[] A,intPintQintR) - { + inttotal_inversions = 0; - + intN1 = q-p+1; A intN2 = RQ; at int[] L =New int[N1]; - int[] R =New int[N2]; - for(inti=0; i<n1; i++) -L[i] = a[p+i]; - for(inti=0; i<n2;i++) -R[i]=a[q+i+1]; in - intI=0; to intJ=0; + intCounter =p; - while(I<l.length && j<r.length) the { * if(l[i]<=R[j]) $ {Panax Notoginsenga[counter]=L[i]; -i++; the } + Else A { thea[counter]=R[j]; +J + +; -Total_inversions + = (q (p+i) +1); $ } $counter++; - } - if(i==l.length) the { - for(intk=j;k<r.length;k++)Wuyia[counter++] =R[k]; the } - Else Wu { - for(intk=i;k<l.length;k++) Abouta[counter++] =L[k]; $ } - returntotal_inversions; - } - Public Static voidMain (string[] args) { A intA[] = {2,3,8,6,1,7,9,1}; + intNum_of_inversions = Inversions (a,0,a.length-1); the System.out.println (num_of_inversions); - } $}
Introduction to algorithms problem 2-4 inversions