How to Sort an Array in Java

Filed Under: Java

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.


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, 6]
[A, E, I, O, U]
Array Sorting In Java

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages