0

I'm trying to print 10,000 random numbers in ascending and descending order using Arrays.sort then output it. If I try it as this, it does not give the right output.

import java.util.*;
import java.util.Random;

public class QuestionFour 
{
    public static void main(String[] args) 
    {
        int arr[] = new int[10000];
        Random rand = new Random();

        for (int i=0; i<10000; i++)
        {
            arr[i] = rand.nextInt( 100 ) + 1;
            Arrays.sort(arr);
            System.out.println(arr);
        }
    }

}
1
  • 1
    @dehasi please delete your comment, This is not how you print an array Commented Oct 31, 2018 at 21:00

2 Answers 2

1

Arrays.sort() does not have anything related with output, it only sorts an array

Let your loop fill the array, and after that sort and print it with Arrays.toString()

int arr[] = new int[10000];
Random rand = new Random();

for (int i=0; i<10000; i++){
    arr[i] = rand.nextInt( 100 ) + 1;
}
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));

Reverse order sort :

  1. You could use Arrays.sort(arr, Comparator.reverseOrder());, but this requires an array of objects, it would requires a Integer arr[] = new Integer[10000]; rather than int

  2. Use a List<Integer> instead of en array, it would be easier to manipulate

    List<Integer> list = new ArrayList<>();
    Random rand = new Random();
    for (int i = 0; i < 10000; i++) {
        list.add(rand.nextInt(100) + 1);
    }
    list.sort(Comparator.reverseOrder());
    System.out.println(list);             //[100, 100, 100, 100, 100, 100, 100, 100 ... 
    
Sign up to request clarification or add additional context in comments.

3 Comments

Why does this print repeating numbers? For ex.: 1,1,1,1,1,1,1,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3........
@tidematic because this is the content of you array, you input 10k element between 1 and 100, this is normal to have a lot of duplicate
If I were to do it in reverse order, how would I use Collections.reverseOrder()?
1

you need to put Arrays.sort(arr); outside your for loop and create another loop for printing the array after it had been sorted. your code should be as follows :

import java.util.*;
import java.util.Random;

public class QuestionFour 
{
    public static void main(String[] args) 
    {
        int arr[] = new int[10000];
        Random rand = new Random();

        for (int i=0; i<10000; i++)
        {
            arr[i] = rand.nextInt( 100 ) + 1;

        }

        Arrays.sort(arr);

        for (int i = 0; i < arr.length; i++) {

            System.out.println(arr[i]);
        }
    }

}

Comments

Your Answer

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