0

I'm a novice at java language, and I had a problem that I have to solve, I'm fairly sure that I've done it right yet the tester still crashes.

a brief summary of what if has to do is " Inside an array a, an inversion is a pair of positions i and j inside the array that satisfy simultaneously both i < j and a[i] > a[j]. In combinatorics, the inversion count inside an array is a rough measure how "out of order" that array is. If an array is sorted in ascending order, it has zero inversions, whereas an n-element array sorted in reverse order has n(n-1)/2 inversions, the largest number possible. This method should count the inversions inside the given array arr, and return that count "

here's what I've done/tried


import java.util.Arrays;

public class P2J1
{
public static int countInversions(int[] arr)
{ 
    int inversions = 0; 
    for (int i = 0; i <= arr.length; i++){
        for (int j = i+1; j < i; j++){
           if (arr[i] > arr[j]){
               inversions++; 
           } 
       } 
   } 
  return inversions; 
} 
}

/// here's the tester 

    @Test public void testCountInversions() {
        Random rng = new Random(SEED);
        CRC32 check = new CRC32();
        for(int i = 0; i < 1000; i++) {
            int[] a = new int[i];
            for(int j = 0; j < i; j++) {
                a[j] = rng.nextInt(100000);
            }
            check.update(P2J1.countInversions(a));
        }
        assertEquals(1579619806L, check.getValue());
    }
1
  • 1
    You need i < arr.length. Also (int j = i+1; j < i; j++) will perform zero iterations, since j < i starts out false. Commented Aug 10, 2019 at 18:53

1 Answer 1

2

In Java, the array indexing is from 0 to arr.length - 1, you need to change i <= arr.length in your code to i < arr.length. Otherwise you would get ArrayIndexOutofBoundsException

Also @khelwood's suggestion is true. Change (int j = i+1; j < i; j++) to (int j = i+1; j < arr.length; j++)

Sign up to request clarification or add additional context in comments.

1 Comment

"In most programming languages" is irrelevant: in this programming language, Java, that is true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.