0

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];
    }
 }

1 Answer 1

3

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.