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 super T> c)
.
Let’s do more details with Java Array Sorting.
Sort with Primitives Java Array
We define a simple Int Java Array:
int[] numbers = new int[] { -9, 5, 4, 8, 11, -2, 2 };
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:
package com.grokonez.sortarray; import java.util.Arrays; public class JavaArraySortingExample { public static void main(String[] args) { int[] numbers = new int[] { -9, 5, 4, 8, 11, -2, 2 }; // Sorting Arrays.sort(numbers); // Print Sorted-Array after Sorting for(int i=0; i // Output -9 -2 2 4 5 8 11Sorting 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.
package com.grokonez.sortarray; import java.util.Arrays; import java.util.List; import com.google.common.collect.Lists; import com.google.common.primitives.Ints; public class JavaArraySortingExample { public static void main(String[] args) { int[] numbers = new int[] { -9, 5, 4, 8, 11, -2, 2 }; // Sort array in ascending order Arrays.sort(numbers); // Use Guava lib to convert Array to List -> then reverse the List Listlist = Ints. asList(numbers); List reverseList = Lists.reverse(list); // Use Guava lib to Convert List to Array numbers = Ints.toArray(reverseList); for(int i=0; i // Output 11 8 5 4 2 -2 -9Use Java 8
- We transform our Array to a Stream and then map it back to an Int array:
package com.grokonez.sortarray; import java.util.Comparator; import java.util.stream.IntStream; public class JavaArraySortingExample { public static void main(String[] args) { int[] numbers = new int[] { -9, 5, 4, 8, 11, -2, 2 }; numbers = IntStream.of(numbers).boxed().sorted(Comparator.reverseOrder()).mapToInt(i->i).toArray(); for(int i=0; iSorting Sub-Array
We can sort a part of Array by using below method interface:
public static void sort(int[] a, int fromIndex, int toIndex)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, exclusiveException:
-IllegalArgumentException
- iffromIndex
>toIndex
-ArrayIndexOutOfBoundsException
- iffromIndex
< 0 ortoIndex
>a.length
package com.grokonez.sortarray; import java.util.Arrays; public class JavaArraySortingExample { public static void main(String[] args) { int[] numbers = new int[] { -9, 5, 4, 8, 11, -2, 2 }; // Sorting Arrays.sort(numbers, 1, 6); for(int i=0; i -9 -2 4 5 8 11 2Sort with String/Objects Array that implement Comparable
Sorting in Ascending Order
With String or Object Array that implement
Comparable
, we can use the method:public static void sort(Object[] a)- 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:
package com.grokonez.sortarray; import java.util.Arrays; public class JavaArraySortingExample { public static void main(String[] args) { String[] strings = new String[] { "elasticsearch", "vue", "python", "angular", "java", "grokonez", "javasampleapproach" }; // Sorting Arrays.sort(strings); for(int i=0; i // output angular elasticsearch fruit grokonez java javasampleapproach python vueSorting 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 withComparator.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.
package com.grokonez.sortarray; import java.util.Arrays; import java.util.List; import com.google.common.collect.Lists; public class JavaArraySortingExample { public static void main(String[] args) { String[] strings = new String[] { "elasticsearch", "vue", "python", "angular", "java", "grokonez", "javasampleapproach" }; // Sorting Arrays.sort(strings); // Use Guava lib to convert Array to List -> then reverse the List Listlist = Arrays.asList(strings); List reverseList = Lists.reverse(list); // Convert List to Array strings = reverseList.toArray(new String[0]); for(int i=0; i // output vue python javasampleapproach java grokonez elasticsearch angularUse Java 8
Java 8 provides the advantage with
Comparator.reverseOrder()
:package com.grokonez.sortarray; import java.util.Arrays; import java.util.Comparator; public class JavaArraySortingExample { public static void main(String[] args) { String[] strings = new String[] { "elasticsearch", "vue", "python", "angular", "java", "grokonez", "javasampleapproach" }; // Sorting Arrays.sort(strings, Comparator.reverseOrder()); for(int i=0; i // Output vue python javasampleapproach java grokonez elasticsearch angularSorting a part of String Array
For sorting a Sub-Array of String/Object(that implements
Comparable
) we use the below method:public static void sort(Object[] a, int fromIndex, int toIndex)-
fromIndex
- the index of the first element (inclusive) to be sorted
-toIndex
- the index of the last element (exclusive) to be sortedException:
-IllegalArgumentException
- iffromIndex
>toIndex
or (optional) if the natural ordering of the array elements is found to violate the Comparable contract
-ArrayIndexOutOfBoundsException
- iffromIndex
< 0 ortoIndex
>a.length
-ClassCastException
- if the array contains elements that are not mutually comparable (for example, strings and integers).Example:
package com.grokonez.sortarray; import java.util.Arrays; public class JavaArraySortingExample { public static void main(String[] args) { String[] strings = new String[] { "elasticsearch", "vue", "python", "angular", "java", "grokonez", "javasampleapproach" }; // Sorting Arrays.sort(strings, 1, 5); for(int i=0; i elasticsearch angular java python vue grokonez javasampleapproach- For descending sorting a sub-array String, we use
Comparator.reverseOrder()
of Java 8:package com.grokonez.sortarray; import java.util.Arrays; import java.util.Comparator; public class JavaArraySortingExample { public static void main(String[] args) { String[] strings = new String[] { "elasticsearch", "vue", "python", "angular", "java", "grokonez", "javasampleapproach" }; // Sorting Arrays.sort(strings, 1, 5, Comparator.reverseOrder()); for(int i=0; i // Output elasticsearch vue python java angular grokonez javasampleapproachSort with Custom Object Java Array
For sorting Objects Array that does NOT implement
Comparable
,we use below method:public staticvoid sort(T[] a, Comparator super T> c) - 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 implementsComparator
:package com.grokonez.sortarray; import java.util.Arrays; import java.util.Comparator; class Customer { private int id; private String name; private int age; public Customer(int id, String name, int age){ this.id = id; this.name = name; this.age = age; } public String toString() { return String.format("id = %d, name = %s, age = %d", this.id, this.name, this.age); } public int getAge() { return age; } } class SortbyAge implements Comparator{ // Used for sorting in ascending order of // AGE public int compare(Customer a, Customer b) { return a.getAge() - b.getAge(); } } public class JavaArraySortingExample{ public static void main(String[] args) { Customer[] customers = new Customer[] { new Customer(1, "Jack", 23), new Customer(7, "Mary", 29), new Customer(3, "Joe", 31), new Customer(9, "Peter", 19), new Customer(2, "Bob", 27) }; // Sorting Arrays.sort(customers, new SortbyAge()); for(int i=0; i -> Output:
id = 9, name = Peter, age = 19 id = 1, name = Jack, age = 23 id = 2, name = Bob, age = 27 id = 7, name = Mary, age = 29 id = 3, name = Joe, age = 31Use Java 8
We can do more simple with the advantage of Java 8 function:
Arrays.sort(customers, Comparator.comparing(Customer::getAge));
Example Code:
package com.grokonez.sortarray; import java.util.Arrays; import java.util.Comparator; class Customer { private int id; private String name; private int age; public Customer(int id, String name, int age){ this.id = id; this.name = name; this.age = age; } public String toString() { return String.format("id = %d, name = %s, age = %d", this.id, this.name, this.age); } public int getAge() { return age; } } public class JavaArraySortingExample { public static void main(String[] args) { Customer[] customers = new Customer[] { new Customer(1, "Jack", 23), new Customer(7, "Mary", 29), new Customer(3, "Joe", 31), new Customer(9, "Peter", 19), new Customer(2, "Bob", 27) }; // Sorting Arrays.sort(customers, Comparator.comparing(Customer::getAge)); for(int i=0; i-> Output:
id = 9, name = Peter, age = 19 id = 1, name = Jack, age = 23 id = 2, name = Bob, age = 27 id = 7, name = Mary, age = 29 id = 3, name = Joe, age = 31Descending Sorting
Define a Descending-Comparator
We just re-define an Descending-Comparator sorting:
package com.grokonez.sortarray; import java.util.Arrays; import java.util.Comparator; class Customer { private int id; private String name; private int age; public Customer(int id, String name, int age){ this.id = id; this.name = name; this.age = age; } public String toString() { return String.format("id = %d, name = %s, age = %d", this.id, this.name, this.age); } public int getAge() { return age; } } class DescendingSortbyAge implements Comparator{ // Used for sorting in ascending order of // AGE public int compare(Customer a, Customer b) { return b.getAge() - a.getAge(); } } public class JavaArraySorting { public static void main(String[] args) { Customer[] customers = new Customer[] { new Customer(1, "Jack", 23), new Customer(7, "Mary", 29), new Customer(3, "Joe", 31), new Customer(9, "Peter", 19), new Customer(2, "Bob", 27) }; // Sorting Arrays.sort(customers, new DescendingSortbyAge()); for(int i=0; i id = 3, name = Joe, age = 31 id = 7, name = Mary, age = 29 id = 2, name = Bob, age = 27 id = 1, name = Jack, age = 23 id = 9, name = Peter, age = 19Use Java 8
With Java 8, we use:
Comparator.comparing(Customer::getAge).reversed()
.- Full Example:
package com.grokonez.sortarray; import java.util.Arrays; import java.util.Comparator; class Customer { private int id; private String name; private int age; public Customer(int id, String name, int age){ this.id = id; this.name = name; this.age = age; } public String toString() { return String.format("id = %d, name = %s, age = %d", this.id, this.name, this.age); } public int getAge() { return age; } } public class JavaArraySorting { public static void main(String[] args) { Customer[] customers = new Customer[] { new Customer(1, "Jack", 23), new Customer(7, "Mary", 29), new Customer(3, "Joe", 31), new Customer(9, "Peter", 19), new Customer(2, "Bob", 27) }; // Sorting Arrays.sort(customers, Comparator.comparing(Customer::getAge).reversed()); for(int i=0; i id = 3, name = Joe, age = 31 id = 7, name = Mary, age = 29 id = 2, name = Bob, age = 27 id = 1, name = Jack, age = 23 id = 9, name = Peter, age = 19Sorting Sub-Array of Custom Object Java Array
For sorting a Sub-Array of Java Object Array, we use below method:
public staticvoid sort(T[] a, int fromIndex, int toIndex, Comparator super T> c) -
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:
package com.grokonez.sortarray; import java.util.Arrays; import java.util.Comparator; class Customer { private int id; private String name; private int age; public Customer(int id, String name, int age){ this.id = id; this.name = name; this.age = age; } public String toString() { return String.format("id = %d, name = %s, age = %d", this.id, this.name, this.age); } public int getAge() { return age; } } public class JavaArraySortingExample { public static void main(String[] args) { Customer[] customers = new Customer[] { new Customer(1, "Jack", 23), new Customer(7, "Mary", 29), new Customer(3, "Joe", 31), new Customer(9, "Peter", 19), new Customer(2, "Bob", 27) }; // Sorting Arrays.sort(customers, 0, 4, Comparator.comparing(Customer::getAge).reversed()); for(int i=0; i id = 3, name = Joe, age = 31 id = 7, name = Mary, age = 29 id = 1, name = Jack, age = 23 id = 9, name = Peter, age = 19 id = 2, name = Bob, age = 27Java 8 Arrays.parallelSort
Java 8 provides a new API interface:
public staticvoid parallelSort(T[] a, int fromIndex, int toIndex, Comparator super T> cmp) - 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.
- TheForkJoin
common pool is used to execute any parallel tasks.Example:
package com.grokonez.sortarray; import java.util.Arrays; import java.util.Comparator; class Customer { private int id; private String name; private int age; public Customer(int id, String name, int age){ this.id = id; this.name = name; this.age = age; } public String toString() { return String.format("id = %d, name = %s, age = %d", this.id, this.name, this.age); } public int getAge() { return age; } } public class JavaArraySorting { public static void main(String[] args) { Customer[] customers = new Customer[] { new Customer(1, "Jack", 23), new Customer(7, "Mary", 29), new Customer(3, "Joe", 31), new Customer(9, "Peter", 19), new Customer(2, "Bob", 27) }; // Sorting Arrays.parallelSort(customers, 0, 4, Comparator.comparing(Customer::getAge).reversed()); for(int i=0; i-> Output:
id = 3, name = Joe, age = 31 id = 7, name = Mary, age = 29 id = 1, name = Jack, age = 23 id = 9, name = Peter, age = 19 id = 2, name = Bob, age = 27