Sort an array in ascending and unfolding order in Java

In this tutorial, we'll look at how to sort an array in ascending and descending order in Java. We'll show you how to use the sort() to accomplish the sorting task.

There are several methods in Java that allow you to sort your arrays, and to use these array sorting methods, you will first need to import a library named Arrays. You do this with the keyword import:

import java.util.Arrays; 
Now that you've imported the Arrays library, you can call the sort() method. It's very easy:

Arrays.sort(myArray); 
Here's some code to try:

import java.util.Arrays; 

public class ArraysTest {

public static void main(String[] args) {

// initialize array
int array[] = {11, 34, 23, 62, 6, 41};

// display all integers before sorting
for (integer : array) {
System.out.println("number: " + integer);
}

// sort array
Arrays.sort(array);

// display all integers after sorting
System.out.println("Sorted array\n");
for (integer int : array) {
System.out.println("number: " + integer);
}
}
}
The for loop at the end will print all the values in each position of the array as output. When the code is executed, it gives this result:

number: 11
number: 34
number: 23
number: 62
number: 6
number: 41
sorted array
number: 6
number: 11
number: 23
number: 34
number: 41
number: 62
As you can see, the array has been sorted in ascending order.
Sorting in descending order is only possible if you write your own code or convert the array into an array of objects, Then import the library Collections and invoke the Collections.sort().

Here's a code that does this:

import java.util.Arrays; 
import java.util.Collections;

public class Tri {

public static void main(String[] args) {

// initialize array
int array[] = {8, 77, 15, 24, 46, 13};

// create an array that contains Integer
Integer[] integerArray = new Integer[array.length];
// display all integers before sorting
// copy all values into an array of type Integer
for (int i=0; i < array.length; i++) {
System.out.println("number: " + array[i]);
//instantiate a new Integer
integerArray[i] = new Integer(array[i]);
}

// sort the array, then reverse it
Arrays.sort(integerArray, Collections.reverseOrder());

// display all integers after sorting
System.out.println("Sorted array\n");
for (integer int: integerArray) {
System.out.println("number: " + integer);
}
}
}
The compilation and execution of this code gives the following result:

number: 8
number: 77
number: 15
number: 24
number: 46
number: 13
Sorted array

number: 77
number: 46
number: 24
number: 15
number: 13
number: 8
References:
Java.util.Arrays.sort(int[]) Method