[Solved] Sort Array of Numbers - Java Task

  

3
Topic starter

Write a program to enter a number n and n integer numbers and sort and print them. Keep the numbers in array of integers: int[].

Examples:

sort an array of numbers example table

1 Answer
2

Here's my solution (the most important line here is the 17th - by using Arrays's class method sort):

import java.util.Arrays;
import java.util.Scanner;
 
public class Pr_01_SortArrayOfNumbers {
 
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
 
        int n = scanner.nextInt();
 
        int[] array = new int[n];
 
        for (int i = 0; i < n; i++) {
            array[i] = scanner.nextInt();
        }
 
        Arrays.sort(array);
 
        System.out.println("Printing with foreach:");
        for (Integer number : array) {
            System.out.print(number + " ");
        }
 
        System.out.println();
        System.out.println("*********************************");
 
        System.out.println("Printing with for:");
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
    }
}
Share: