Reputation: 17268
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class InversionCounter {
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(new File("src/IntegerArray.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int [] nums = new int [100000];
int i = 0;
while(scanner.hasNextInt()){
nums[i++] = scanner.nextInt();
}
System.out.println(countInversions(nums));
}
public static int countInversions(int[] nums) {
int count = 0;
for (int i=0;i<nums.length-1;i++) {
for (int j=i+1;j<nums.length;j++) {
if (nums[i]>nums[j]) {
count++;
}
else {continue;}
}
}
return count;
}
}
The code above reads 100,000 integers from a file and counts the inversions for this array of integers. The output is probably a very large number like 1198233847 and should definitely be positive. However, it outputs a negative one like -1887062008. The program logic is likely to be correct as I have tried other algorithms for the same purpose and got the same negative number as output. I suspect that the result is too big a positive number and as a result Java converts it to a negative one.
Upvotes: 2
Views: 2508
Reputation: 30580
The worst case here is 4,999,950,000 inversions, which is bigger than int's max value (2,147,483,647). You should probably use a long to store the number.
Upvotes: 2
Reputation: 55223
The max value of an int
is 2,147,483,647 - what you are seeing is overflow. You should make count
a long
if you expect it to be so big.
source: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Upvotes: 3