面试常考:归并排序的思想(分治)

image

import java.util.Arrays;

//小和问题
public class SmallSort {

    public static void main(String[] args) {
        int[] arr = {1,3,4,2,5};
        System.out.println(Arrays.toString(arr));
//        merge(arr, 0, 3, arr.length-1);
        int res = mergeSort(arr, 0, arr.length-1);
        System.out.println(res);
    }
    
    //归并排序
    public static int mergeSort(int[] arr,int low, int heigh){
        if (low>=heigh) {
            return 0;
        }
        int mid = (low+heigh)/2;
//        if (low<heigh) {
//            //处理第一个数组
//            mergeSort(arr, low, mid);
//            //处理第二个数组
//            mergeSort(arr, mid+1, heigh);
//            //归并
//            merge(arr, low, mid, heigh);
            //return mergeSort(arr, low, mid)+mergeSort(arr, mid+1, heigh)+merge(arr, low, mid, heigh);
            
//        }
        return mergeSort(arr, low, mid)+mergeSort(arr, mid+1, heigh)+merge(arr, low, mid, heigh);
        
    }
    
    //将两个排好序的数组合并,在合并的过程中求小和
    public static int merge(int[] arr,int low,int mid ,int heigh){
        //第一个数组的下标
        int i = low;
        //第二个数组的下标
        int j = mid+1;
        //新数组
        int[] temp = new int[heigh-low+1];
        //新数组的下标
        int k = 0;
        //小和
        int res = 0;
        
        while (i<=mid&&j<=heigh) {
            if (arr[i]<arr[j]) {
                temp[k++] = arr[i];
                res =res + arr[i]*(heigh-j+1);
                i++;
            }else {
                temp[k++] = arr[j++];
            }
        }
        
        //某个数组还没有放完
        while (i<=mid) {
            temp[k++] = arr[i++];
        }
        while (j<=heigh) {
            temp[k++] = arr[j++];
        }
        
        //最后把排好序的temp赋给arr
        for (int m=0;m<temp.length;m++){
            arr[low+m] = temp[m];
        }
        return res;
    }
}
posted on 2019-05-05 20:52  源格  阅读(158)  评论(0编辑  收藏  举报