In Java, we can use various methods to sort elements of an array in both ascending and descending order. Below, we will explore code examples for each sorting method, along with explanations and outputs.
Sorting Elements of an Array in Ascending Order in Java
Using Arrays.sort()
The simplest way to sort an array in ascending order is by using the Arrays.sort() method from the Java Standard Library. This method sorts the array in place.
Code Example
import java.util.Arrays;
public class AscendingOrder {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 10}; // Unsorted array
// Sorting the array in ascending order
Arrays.sort(arr);
// Displaying the sorted array
System.out.println("Array sorted in ascending order: " + Arrays.toString(arr));
}
}
Explanation
- Importing Arrays Class: We import java.util.Arrays to access the sorting functionality.
- Defining the Array: An unsorted integer array is defined.
- Sorting: The Arrays.sort(arr) method sorts the array in ascending order.
- Displaying Results: The sorted array is printed using Arrays.toString(arr) for easy readability.
Output
Sorting Elements of an Array in Descending Order in Java
Using Arrays.sort() with Collections.reverseOrder()
To sort an array in descending order, we can use the Arrays.sort() method along with Collections.reverseOrder(). Note that this requires using Integer objects instead of primitive int types.
Code Example
import java.util.Arrays;
import java.util.Collections;
public class DescendingOrder {
public static void main(String[] args) {
Integer[] arr = {5, 2, 8, 1, 10}; // Unsorted array (Integer type)
// Sorting the array in descending order
Arrays.sort(arr, Collections.reverseOrder());
// Displaying the sorted array
System.out.println("Array sorted in descending order: " + Arrays.toString(arr));
}
}
Explanation
- Importing Classes: We import java.util.Arrays and java.util.Collections to utilize sorting functionalities.
- Defining the Array: An unsorted integer array is defined using Integer objects.
- Sorting: The Arrays.sort(arr, Collections.reverseOrder()) method sorts the array in descending order.
- Displaying Results: The sorted array is printed using Arrays.toString(arr).
Output
Summary
- Ascending Order: The Arrays.sort() method efficiently sorts an array of integers in ascending order.
- Descending Order: To sort an array in descending order, we convert it to an Integer type and use Arrays.sort() with Collections.reverseOrder().
These methods provide a straightforward approach to sorting arrays in Java while leveraging built-in functionalities for efficiency and simplicity.