简体   繁体   中英

Java array.sort(arr) output 0 instead of arr

I am using Java array.sort on a random int generated array.

The result should be a sorted array but instead i get 0's and a few random generated numbers.

Here is my code:

public class test {
    public static void main(String[] args) {
        int[] list = new int[10];
        Random rand = new Random(); 
        for (int i = 0; i < list.length; i++) {
            list[i] = rand.nextInt(100);
            Arrays.sort(list); 
            System.out.println(list[i]);
        }  
    }
}

Expected outpit should be a sorted array of 10 random integers but intead always get first 5 numbers as 0.

Can anyone help?

It looks like you're sorting the entire array on every iteration. Try sorting & printing the array after setting the values.

public class test {
    public static void main(String[] args) {
        int[] list = new int[10];
        Random rand = new Random(); 
        for (int i = 0; i < list.length; i++) {
            list[i] = rand.nextInt(100);
        }  

        Arrays.sort(list); 

        for (int i = 0; i < list.length; i++) {
            System.out.println(list[i]);
        } 
    }
}

If you debug your application you can see why you're getting 5 0's every time.

int[] list = new int[10]; produces an array of [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], and before printing you sort the array. So, the first 5 ( list[0] , list[1] , list[2] ...) will be 0 , while list[6] list[7] .. will be the result of rand.nextInt(100)

The problem is you're sorting the array while you're populating it with random numbers.

The reason why this doesn't work is because the initial value of an element of an int array is 0 and your array will look like this when you first initialize it:

[0, 0, 0, 0, 0, ...]

Then during the first round of the loop, let's say 5 is generated as the random number and the first element is initialized to 5. The array now looks like this:

[5, 0, 0, 0, 0, ...]

The list is then sorted before the the loop continues, meaning the 5 in the first element is sent to the end of the list, and the first element is replaced with a 0 like so:

[0, 0, 0, ... 0, 5]

The way to fix this would be to sort the array after you poppulated it with random numbers like so:

public class test {
public static void main(String[] args) {
    int[] list = new int[10];
    Random rand = new Random(); 
    for (int i = 0; i < list.length; i++) {
        list[i] = rand.nextInt(100);
    }  

    Arrays.sort(list); 
    System.out.println(Arrays.toString(list));
}

}

Hope this helped!

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