1

I am trying to find out the number of inversion in any array. I have applied mergesort. And when merging the sub arrays I counted the number if any value of right subarray is less than any value of left sub array. This code does not work if the array contains a lot of data.

private static long getNumberOfInversions(int[] a, int[] b, int left,
                int right)
{
    long numberOfInversions = 0;
    if (right > left)
    {
        int ave = (left + right) / 2;
        numberOfInversions = getNumberOfInversions(a, b, left, ave);
        numberOfInversions += getNumberOfInversions(a, b, ave + 1, right);
        numberOfInversions += merge(a, b, left, ave + 1, right);
    }
    return numberOfInversions;
}

public static long merge(int[] a, int b[], int left, int ave, int rigth)
{
    int i = 0, j = left, k = ave;
    long count = 0;
    while (j <= ave - 1 && k <= rigth)
    {
        if (a[j] <= a[k])
        {
            b[i] = a[j];
            i++;
            j++;
        }
        else
        {
            b[i] = a[k];
            count += ave - j;
            i++;
            k++;
        }
    }
    while (j <= ave - 1)
    {
        b[i] = a[j];
        i++;
        j++;

    }
    while (k <= rigth)
    {
        b[i] = a[k];
        i++;
        k++;
    }
    while (left <= rigth)
    {
        a[left] = b[i];
        left++;
        i++;
    }
    return count;
}

public static void main(String[] args)
{
    Scanner scanner = new Scanner(System.in);
    int n = scanner.nextInt();
    int[] a = new int[n];
    for (int i = 0; i < n; i++)
    {
        a[i] = scanner.nextInt();
    }
    int[] b = new int[n];
    System.out.println(getNumberOfInversions(a, b, 0, n - 1));
}
Burkhard
  • 14,596
  • 22
  • 87
  • 108
  • did you try to use IDE debug to investigate your code behavior? did you write any test for your code? – ursa Jun 11 '16 at 23:13
  • I tested my code. When a large data set is given it gives wrong answer. but I cant find the error of my logic –  Jun 12 '16 at 07:05
  • Please provide a [mcve] You should also consider using [System.arrayCopy](https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#arraycopy-java.lang.Object-int-java.lang.Object-int-int-) –  Dec 14 '16 at 06:37

0 Answers0