小和问题
public class SmallSum { public static void mergeSort(int[] arr) { if (arr == null || arr.length < 2) { return; } mergeSort(arr, 0, arr.length - 1); } static int sum=0; static void mergeSort(int a[],int l,int r) { if(l==r) { return; } int m = l+((r-l)>>1); mergeSort(a, l, m); mergeSort(a, m+1, r); merge(a,l,m,r); } static void merge(int a[],int l,int m,int r) { int[] help = new int[r-l+1]; int p1=l; int p2=m+1; int i=0; while(p1<=m&&p2<=r) { sum+=a[p1]<a[p2]?a[p1]*(r-p2+1):0; help[i++] = a[p1]<a[p2]?a[p1++]:a[p2++]; } while(p1<=m) { help[i++]=a[p1++]; } while(p2<=r) { help[i++]=a[p2++]; } for(i=0;i<r-l+1;i++) { a[l+i]=help[i]; } } public static void main(String[] args) { int a[] = {1,3,4,2,5}; mergeSort(a); System.out.println(sum); } }