题目描述
思路分析
代码实现
package class02;import java.util.Arrays;
import java.util.concurrent.locks.ReentrantLock;/*** @创建人 wdl* @创建时间 2021/4/13* @描述*/
public class Demo02SmallSum {public static int mergeSort(int[] arr){if(arr==null|| arr.length<2){return 0;}return process(arr,0,arr.length-1);}//arr[L..R]既要排好序,也要求小和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 M,int R){int [] help=new int[R-L+1];int i=0;int p1=L;int p2=M+1;int res=0;while (p1<=M&&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<=M){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;}public static void main(String[] args) {int []arr={1,5,6,2,3,4,4};int i = mergeSort(arr);System.out.println(i);System.out.println(Arrays.toString(arr));}}