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());
}
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++)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.