简体   繁体   中英

Counting Inversions for an Array of 100,000 Integers, Why Get a Negative Output?

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.

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

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM