user9206222
user9206222

Reputation:

How to output using Arrays.sort

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

}

Upvotes: 0

Views: 322

Answers (2)

azro
azro

Reputation: 54168

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 ... 
    

Upvotes: 1

Mohammed Fathi
Mohammed Fathi

Reputation: 1475

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

}

Upvotes: 1

Related Questions