简体   繁体   中英

Cannot sort array with randomly generated numbers

I am having trouble getting the array to sort after the random numbers are generated in the array. I think the array is being sorted before all the numbers are assigned. I have tried nesting another for loop inside of the main one also, but I either get the same result or an endless loop of random numbers.

public static void main(String[] args) {
    int[] anArray;
    anArray = new int[10000];
    Random generator= new Random();

    for(int i=0; i<10000; i++){
       anArray [i]= (generator.nextInt(98)+1);
       java.util.Arrays.sort(anArray);
       System.out.println(anArray[i];
    }
 }

You need to take java.util.Arrays.sort(anArray); outside of the loop, or you will sort at each step and the i-th element will not be what you just added:

for(int i=0; i<10000; i++){
   anArray [i]= (generator.nextInt(98)+1);
}
java.util.Arrays.sort(anArray);
System.out.println(Arrays.toString(anArray));

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