Search code examples
javaarrayssortingdouble

java.util.Arrays.sort doesn't sort an array of doubles properly


Link to the full test case:

test case

The test case consists of 2500 values, all being above 0. The problem I have is: It doesn't sort properly. Neither with a coded sorting algorithm, nor with the Arrays.sort function.

How does this happen and how do I fix this? The result I'm getting is the following:

The output shows the following:

0.0 0.0 0.0 46.0 54.0 118.0 141.0 220.0 259.0 273.0 ...

There are no zeros in the array. Also the amount of 3 digit numbers is way lower in the test case than in the sorted array. This is the snippet for the code.

The interesting thing being: I've debugged the input already, reading in the input works without problems, however after the sorting, the whole array is broken and the values are all incorrect.

This is the code snippet:

public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt(); 
            double[] inarr = new double[n];
            double sum = 0;
            
            for (int i = 0; i<n; i++){
                if (sc.hasNextDouble()){
                    inarr[i] = sc.nextDouble();
                }
                
                sum += inarr[i];
            }
            
            // for (int i = 0; i<n; i++){
            //     System.out.println(inarr[i]);
            // }
            
            Arrays.sort(inarr);
            
            for (int i = 0; i<n; i++){
                System.out.println(inarr[i]);
            }

Thanks in advance for your help!


Solution

  • One issue could be

    for (int i = 0; i<n; i++){
        if (sc.hasNextDouble()){
            inarr[i] = sc.nextDouble();
        }
        sum += inarr[i];
    } 
    

    I don't know what environment you are running this in, but if there is any issue with your stdin you may skip values here. Ie, if sc.hasNextDouble() returns false for any reason you are still incrementing your i and the current place in the inarray stays at 0 ...

    Add a counter and check how many values you are actually reading

    int readCount = 0;
    for (int i = 0; i<n; i++){
        if (sc.hasNextDouble()){
            inarr[i] = sc.nextDouble();
            readCount++;
        }
        sum += inarr[i];
    } 
    System.out.println(readCount);
    

    In your case you probably will receive a readCount that is less than n. Again, as we don't know your environment or how you get your data into stdin, I cannot help you solve this issue. But I can assure you, Arrays.sort won't create new numbers in the array.