Small sum problem (example of merge sort)

The small sum problem
is in an array. The numbers to the left of each number that are smaller than the current number are added up, which is called the small sum of the array.
Find the small sum of an array .
Example:
[1,3,4,2,5]
The number on the left of 1 is less than 1, no; the number
on the left of 3 is less than 3, 1; the number
on the left of 4 is less than 4, 1, 3; the number on the
left of 2 is less than 2 The number of , 1; the number to the
left of 5 smaller than 5, 1, 3, 4, 2;

So the small sum is 1+1+3+1+1+3+4+2=16

If you directly scan it with two layers of for loops, the time complexity is O(n*n). This problem can be reduced to O(nlogn) by using merge sort.

code above

import java.io.BufferedInputStream;
import java.util.Scanner;

public class test {
    public static int[] help;

    public static int mergeSort(int[] a) {
        if (a == null || a.length < 2) {
            return 0;
        }
        help = new int[a.length];
        return sort(a, 0, a.length - 1);
    }

    public static int sort (int [] a, int lo, int hi) {
        if (lo >= hi) {
            return 0;
        }
        int mid = lo + ((hi - lo) >> 1);
        return sort(a, lo, mid) + sort(a, mid + 1, hi) + merge(a, lo, mid, hi); // each part is sorted when returning to the large interval
    }

    public static int merge(int[] a, int lo, int mid, int hi) {
        int j = lo, k = mid + 1, res = 0;
        for (int i = lo; i <= hi; ++i) {
            help[i] = a[i];
        }
        for (int i = lo; i <= hi; ++i) {
            if (j > mid) {
                a[i] = help[k++];
            } else if (k > hi) {
                a[i] = help[j++];
            } else if (help[j] < help[k]) {
                res += (hi - k + 1) * help[j]; // all numbers between k~hi are greater than help[j], res is the sum of the numbers in front of help[j] less than it
                a[i] = help[j++];
            } else {
                a[i] = help[k++];
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Scanner cin = new Scanner(new BufferedInputStream(System.in));
        int n = cin.nextInt(); // number to sort
        int[] a = new int[n]; // If you want to sort strings with String[], double with Double[], and so on, it becomes a general-purpose sorted array
        for (int i = 0; i < n; ++i) {
            a [i] = cin.nextInt ();
        }
        cin.close();
        System.out.println(mergeSort(a)); // The decimal sum has been calculated when sorting is done
        /*if (n != 0) {
            System.out.print(a[0]);
        }
        for (int i = 1; i < n; ++i) {
            System.out.print(" " + a[i]);
        }*/
    }
}



============================== I am a slow programmer ============= =============

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325851886&siteId=291194637