Java Sorting Array Program
Java Program to Sort an Array
We will use the
Arrays.sort()
method to sort the array in ascending
order. The
Arrays.sort()
method is a built-in method in
Java
that sorts the specified array of
objects into ascending order. The sorting algorithm used by this method is a modified merge
sort
algorithm.
We will also learn how to sort an array in descending order
using the Arrays.sort()
method by passing the Collections.reverseOrder()
method as a second argument.
public class SortArray {
public static void main(String[] args) {
Integer[] numbers = {5, 2, 8, 1, 6, 3, 7, 4};
System.out.println("Original Array: " + Arrays.toString(numbers));
// Sort the array in ascending order
Arrays.sort(numbers);
System.out.println("Sorted Array (Ascending Order): " + Arrays.toString(numbers));
// Sort the array in descending order using Arrays.sort() method
Arrays.sort(numbers, Collections.reverseOrder());
System.out.println("Sorted Array (Descending Order): " + Arrays.toString(numbers));
}
}
Original Array: [5, 2, 8, 1, 6, 3, 7, 4] Sorted Array (Ascending Order): [1, 2, 3, 4, 5, 6, 7, 8] Sorted Array (Descending Order): [8, 7, 6, 5, 4, 3, 2, 1]Time Complexity: O(nlogn) - The time complexity of the
Arrays.sort()
method is O(nlogn) where n is the number of
elements in the array so the time complexity of this program is also O(nlogn).
Space Complexity: O(n) - The space complexity of this program is O(n) where n is the number of elements in the array as we are using an extra array to store the sorted array.
- Recommended Links
- Selenium Interview Questions