How to Sort an Array in Java With Examples

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.

Output of the above program is:

 

Array Sorting In Java

Important Points

  1. We can use Arrays.sort(T[] tArr) only if the array type implements Comparable interface.
  2. There is another variant of Arrays.sort(T[] tArr, Comparator c) that we can use to sort custom object array based on different fields.
  3. You can head over to java comparable and comparator to learn about sorting an array using Comparator.
  4. 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:

  1. Bubble Sort
  2. Insertion Sort
  3. Heap Sort
  4. Merge Sort
  5. 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.

By admin

Leave a Reply