-1

I'm trying to count the number of inversions in an array. I'm getting the result of 3 when it should be 4. Here's my code.

 int[] array1 = new int[5];
 array1[0] = 3;
 array1[1] = 7;
 array1[2] = 10;
 array1[3] = 6;
 array1[4] = 4;

 int count = 0;
for(int i =0;i<array1.length;i++){

    for(int j =i+1;j<array1.length;j++){

        if(array1[i]> array1[j] ){

        count++;
    }
}
}
System.out.println(count);

Anyone know why its doing this? thanks

lc112
  • 11
  • 2

2 Answers2

0

The i++ and j++ index incrementation should not be repeated in the body of your for loops as they already exist in the same line of the for loop conditions.

Ling Zhong
  • 1,744
  • 14
  • 24
0

Remove j++ and i++. Also change the initial position of j to i+1, instead of 0.

int[] array1 = new int[5];
array1[0] = 3;
array1[1] = 7;
array1[2] = 10;
array1[3] = 6;
array1[4] = 4;

int count = 0;
for(int i =0;i<array1.length;i++){

    for(int j=i+1;j<array1.length;j++){

       if(array1[i]> array1[j] ){
          count++;
       }

    }
 }
 System.out.println(count);
Andrew Lobley
  • 342
  • 4
  • 12
  • I had done what you suggested before hand and I was getting 6, but from changing j from 1 to i + 1 it worked :d thanks a lot – lc112 Nov 08 '15 at 22:42