How to Sort an Array in Java with Examples

java-array-sorting-feature-img-new


In the tutorial, we will discuss how to Sort an Array with Java in ascending and descending order. java.util.Arrays class provides a lot of Methods to sort an Array with difference types:

  • With Primitives Array, We use the method such as: static void sort(int[] a).
  • With String or Objects Array that implement Comparable, We use method: static void sort(Object[] a).
  • With Custom Object Array that no implement Comparable, We use method: sort(T[] a, Comparator c).

Let’s do more details with Java Array Sorting.

Sort with Primitives Java Array

We define a simple Int Java Array:

Sorting in Ascending Order

We use the method static void sort(int[] a) to sort the specified array into ascending numerical order.
– The method returns nothing
– The Sorting algorithm is a Dual-Pivot Quicksort
– This algorithm offers O(n log(n)) performance so it is typically faster than traditional (one-pivot) Quicksort implementations.

Practice:

Sorting in Descending Order

Java doesn’t support the use of Comparators on primitive types so sorting a primitive array in descending order is not easy.

We have 2 approaches:

Use Guava lib

– Sorting Java Array in ascending order. Then use Guava lib to convert Array to List, reverse the List and finally convert the reversed-list to Java Array.

Use Java 8

– We transform our Array to a Stream and then map it back to an Int array:

Sorting Sub-Array

We can sort a part of Array by using below method interface:

It sorts the specified range of the array into ascending order. If fromIndex == toIndex, the range to be sorted is empty.

fromIndex – the index of the first element, inclusive
toIndex – the index of the last element, exclusive

Exception:
IllegalArgumentException – if fromIndex > toIndex
ArrayIndexOutOfBoundsException – if fromIndex < 0 or toIndex > a.length

Sort with String/Objects Array that implement Comparable

Sorting in Ascending Order

With String or Object Array that implement Comparable, we can use the method:

– Sorts the specified array of objects into ascending order, according to the natural ordering of its elements
– All elements in the array must implement the Comparable interface.
– According to Oracle: “This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons.”

Exception:
ClassCastException – if the array contains elements that are not mutually comparable (for example, strings and integers)
IllegalArgumentException – if the natural ordering of the array elements is found to violate the Comparable contract (optional).

Example with String Array Sorting:

Sorting in Descending Order

– With String or Object that implement Comparable, for Sorting in Descending Order, we can use above approach with the supporting of Guave lib. Or using the advantage of Java 8 with Comparator.reverseOrder().

Using Guava lib

– Sorting Java String/Object Array in ascending order. Then use Guava lib to convert Array to List, reverse the List and finally convert the reversed-list to Java Array.

Use Java 8

Java 8 provides the advantage with Comparator.reverseOrder():

Sorting a part of String Array

For sorting a Sub-Array of String/Object(that implements Comparable) we use the below method:

fromIndex – the index of the first element (inclusive) to be sorted
toIndex – the index of the last element (exclusive) to be sorted

Exception:
IllegalArgumentException – if fromIndex > toIndex or (optional) if the natural ordering of the array elements is found to violate the Comparable contract
ArrayIndexOutOfBoundsException – if fromIndex < 0 or toIndex > a.length
ClassCastException – if the array contains elements that are not mutually comparable (for example, strings and integers).

Example:

– For descending sorting a sub-array String, we use Comparator.reverseOrder() of Java 8:

Sort with Custom Object Java Array

For sorting Objects Array that does NOT implement Comparable,we use below method:

– It sorts the specified array of objects according to the order induced by the specified comparator.
– The comparator is used to determine the order of the array.
– According to Oracle: “This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons.”

Sorting Example with Custom Object

Create a Comparator class

We define an SortbyAge class that implements Comparator:

-> Output:

Use Java 8

We can do more simple with the advantage of Java 8 function:
Arrays.sort(customers, Comparator.comparing(Customer::getAge));

Example Code:

-> Output:

Descending Sorting

Define a Descending-Comparator

We just re-define an Descending-Comparator sorting:

Use Java 8

With Java 8, we use: Comparator.comparing(Customer::getAge).reversed().

– Full Example:

Sorting Sub-Array of Custom Object Java Array

For sorting a Sub-Array of Java Object Array, we use below method:

fromIndex – the index of the first element (inclusive) to be sorted
toIndex – the index of the last element (exclusive) to be sorted
c – the comparator to determine the order of the array.

Example:

Java 8 Arrays.parallelSort

Java 8 provides a new API interface:

– The sorting algorithm is a parallel sort-merge that breaks the array into sub-arrays that are themselves sorted and then merged. When the sub-array length reaches a minimum granularity, the sub-array is sorted by Arrays.sort method.
– The ForkJoin common pool is used to execute any parallel tasks.

Example:

-> Output:



By grokonez | March 19, 2019.


Related Posts


Got Something To Say:

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

*