Sarvnashak
Sarvnashak

Reputation: 829

What is wrong with my algorithm for counting inversion?

The code is working fine for test cases like {3,3,3,3}, {1,2,3,4}, {2,4,1,3,5} etc. But it isn't working for {1,20,6,4,5,2,7,3,5}, which should return 18 inversions. My code is getting me 16 inversions.

class Test{ 
    static int count =0;

    public static void main(String[] agrs) {
        int[] arr = new int[] {1,20,6,4,5,2,7,3,5};                
        sort(arr);
        System.out.println("\n"+count);
    }

    private static void sort(int[] arr) {
        int length = arr.length;
        int tempArr[] = new int[length];
        divideAndConquer(arr,tempArr,0,length-1);
    }

    private static void divideAndConquer(int[] arr, int[] tempArr, int low, int high) {
        if(low < high){
            int middle = low + (high - low) / 2;
            divideAndConquer(arr, tempArr, low, middle);
            divideAndConquer(arr, tempArr, middle + 1, high);
            merge(arr, tempArr, low, middle, high);
        }
    }

    private static void merge(int[] arr, int[] tempArr, int low, int middle,int high) {
        for (int i = low; i <= high; i++)
                tempArr[i] = arr[i];

        int i = low, j = middle + 1, k = low;

        while (i <= middle && j <= high) {
            if(tempArr[i] < tempArr[j]) {
                arr[k] = tempArr[i];
                i++;
            }
            else {
                arr[k] = tempArr[j];
                if(tempArr[i] != tempArr[j])
                count += middle+1 - i;  
                System.out.println(count);
                j++;
            }
            k++;
        }

        while (i <= middle) {
            arr[k] = tempArr[i];
            k++;
            i++;
        }
    }
}

Upvotes: 0

Views: 81

Answers (1)

ROMANIA_engineer
ROMANIA_engineer

Reputation: 56694

Just change the line

if(tempArr[i] < tempArr[j]) {

to

if(tempArr[i] <= tempArr[j]) {

and the problem will be solved.

Upvotes: 1

Related Questions