利用归并排序思想解决小和问题
小和问题:在一个数组中,一个数左边比它小的数的总和,叫数的小和,所有数的小和累加起来,叫数组小和,求一个数组的组小和
public class SMall {
public static void main(String[] args) {
int[] arr = {33,4,6,5,67,7,6,7,6,65,7,78,8,8,7,6,5,4,4,5,56,6,67,78};
int res = smallSum(arr);
System.out.println(res);
}
public static int smallSum(int[] arr){
if(arr==null || arr.length<2){
return 0;
}
return process(arr, 0, arr.length-1);
}
public static int process(int[] arr, int L, int R){
if(L==R){
return 0;
}
int mid = L + ((R-L)>>1);
return process(arr, L, mid) + process(arr, mid+1, R) + merge(arr, L, mid, R);
}
public static int merge(int[] arr, int L, int mid, int R){
int[] help = new int[R-L+1];
int i = 0;
int p1= L;
int p2 = mid + 1;
int res = 0;
while(p1 <= mid && p2<=R){
res += arr[p1]<arr[p2] ? arr[p1]*(R-p2+1):0;
help[i++] = arr[p1]<arr[p2] ? arr[p1++] : arr[p2++];
}
while(p1 <=mid ){
help[i++] = arr[p1++];
}
while(p2 <= R){
help[i++] = arr[p2++];
}
for(i=0; i<help.length; i++){
arr[L+i] = help[i];
}
return res;
}
}