Java Array is like a container that can hold a fixed number of the same type of items, it can be primitive types as well as Objects.
Array Sorting in Java
Sometimes we need to sort array in java, we can use Arrays class to sort the array. Arrays is a utility class that provides a lot of useful methods to work with arrays in java.
Let’s look at an example to sort an array in Java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.journaldev.sort; import java.util.Arrays; public class JavaArraySort { /** * This class shows how to sort an array in Java * @param args */ public static void main(String[] args) { int[] intArr = {1, 4, 2, 6, 3}; String[] strArr = {"E", "A", "U","O","I"}; //sort int array Arrays.sort(intArr); Arrays.sort(strArr); System.out.println(Arrays.toString(intArr)); System.out.println(Arrays.toString(strArr)); } } |
Output of the above program is:
1 2 3 4 5 |
<span style="color: #008000;"><strong><code> [1, 2, 3, 4, 6] [A, E, I, O, U] <img class="alignnone wp-image-31760 size-full" src="https://all-learning.com/wp-content/uploads/2012/11/array-sorting-in-javas.png" alt="array-sorting-in-java" width="1200" height="672" /> </code></strong></span> |
Array Sorting In Java
Important Points
- We can use
Arrays.sort(T[] tArr)
only if the array type implements Comparable interface. - There is another variant of
Arrays.sort(T[] tArr, Comparator c)
that we can use to sort custom object array based on different fields. - You can head over to java comparable and comparator to learn about sorting an array using Comparator.
Arrays.sort(T[] t)
uses Dual-Pivot Quicksort algorithm with performance of O(n log(n)). The sorting is done in natural ascending order.
What are different ways to sort an array in Java?
There are many algorithms to sort an array. Some of the popular ones are:
- Bubble Sort
- Insertion Sort
- Heap Sort
- Merge Sort
- Quick Sort
We can write code to implement any of these algorithms to sort an array. However, it’s always recommended to use built-in Arrays.sort() function for error-free sorting and fast performance.