How to Sort an Array in Java with Examples

java-array-sorting-feature-img-new

[no_toc]
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:


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.ozenero.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<numbers.length; i++) {
			System.out.println(numbers[i]);	
		}
	}
}

Output:


// Output
-9
-2
2
4
5
8
11

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.

package com.ozenero.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
		List<Integer> list = Ints. asList(numbers);
		List<Integer> reverseList = Lists.reverse(list);
		
		// Use Guava lib to Convert List to Array
		numbers = Ints.toArray(reverseList);
		
		for(int i=0; i<numbers.length; i++) {
			System.out.println(numbers[i]);	
		}
	}
}

// Output
11
8
5
4
2
-2
-9

Use Java 8

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

package com.ozenero.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; i<numbers.length; i++) {
			System.out.println(numbers[i]);	
		}
	}
}

Sorting 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, exclusive

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

package com.ozenero.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<numbers.length; i++) {
			System.out.println(numbers[i]);	
		}
	}
}

-9
-2
4
5
8
11
2

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:


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.ozenero.sortarray;

import java.util.Arrays;

public class JavaArraySortingExample {
	public static void main(String[] args) {
		String[] strings = new String[] { "elasticsearch", "vue", "python", "angular", "java", "ozenero", "javasampleapproach" };

		// Sorting
		Arrays.sort(strings);
		
		for(int i=0; i<strings.length; i++) {
			System.out.println(strings[i]);	
		}
	}
}

// output
angular
elasticsearch
fruit
ozenero
java
javasampleapproach
python
vue

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.

package com.ozenero.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", "ozenero", "javasampleapproach" };

		// Sorting
		Arrays.sort(strings);
		
		// Use Guava lib to convert Array to List -> then reverse the List
		List<String> list = Arrays.asList(strings);
		List<String> reverseList = Lists.reverse(list);
		
		// Convert List to Array
		strings = reverseList.toArray(new String[0]);
		
		for(int i=0; i<strings.length; i++) {
			System.out.println(strings[i]);	
		}
	}
}

// output
vue
python
javasampleapproach
java
ozenero
elasticsearch
angular

Use Java 8

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

package com.ozenero.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", "ozenero", "javasampleapproach" };

		// Sorting
		Arrays.sort(strings, Comparator.reverseOrder());
		
		for(int i=0; i<strings.length; i++) {
			System.out.println(strings[i]);	
		}
	}
}

// Output
vue
python
javasampleapproach
java
ozenero
elasticsearch
angular

Sorting 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 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:

package com.ozenero.sortarray;

import java.util.Arrays;

public class JavaArraySortingExample {
	public static void main(String[] args) {
		String[] strings = new String[] { "elasticsearch", "vue", "python", "angular", "java", "ozenero", "javasampleapproach" };

		// Sorting
		Arrays.sort(strings, 1, 5);
		
		for(int i=0; i<strings.length; i++) {
			System.out.println(strings[i]);	
		}
	}
}

elasticsearch
angular
java
python
vue
ozenero
javasampleapproach

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

package com.ozenero.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", "ozenero", "javasampleapproach" };

		// Sorting
		Arrays.sort(strings, 1, 5, Comparator.reverseOrder());
		
		for(int i=0; i<strings.length; i++) {
			System.out.println(strings[i]);	
		}
	}
}

// Output
elasticsearch
vue
python
java
angular
ozenero
javasampleapproach

Sort with Custom Object Java Array

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


public static  void sort(T[] a,
            Comparator 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 implements Comparator:


package com.ozenero.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<Customer> { 
    // 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<customers.length; i++) {
			System.out.println(customers[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 = 31

Use 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.ozenero.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<customers.length; i++) {
			System.out.println(customers[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 = 31

Descending Sorting

Define a Descending-Comparator

We just re-define an Descending-Comparator sorting:

package com.ozenero.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<Customer> { 
    // 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<customers.length; i++) {
			System.out.println(customers[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 = 19

Use Java 8

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

– Full Example:

package com.ozenero.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(&quot;id = %d, name = %s, age = %d&quot;, 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, &quot;Jack&quot;, 23),
				new Customer(7, &quot;Mary&quot;, 29),
				new Customer(3, &quot;Joe&quot;, 31),
				new Customer(9, &quot;Peter&quot;, 19),
				new Customer(2, &quot;Bob&quot;, 27)
				
		};
		
		// Sorting
		Arrays.sort(customers, Comparator.comparing(Customer::getAge).reversed());
		
		for(int i=0; i&lt;customers.length; i++) {
			System.out.println(customers[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 = 19

Sorting Sub-Array of Custom Object Java Array

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


public static  void sort(T[] a,
            int fromIndex,
            int toIndex,
            Comparator 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.ozenero.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<customers.length; i++) {
			System.out.println(customers[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 = 27

Java 8 Arrays.parallelSort

Java 8 provides a new API interface:


public static  void parallelSort(T[] a, int fromIndex, int toIndex,
                                        Comparator 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.
– The ForkJoin common pool is used to execute any parallel tasks.

Example:

package com.ozenero.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<customers.length; i++) {
			System.out.println(customers[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

One thought on “How to Sort an Array in Java with Examples”

  1. Howdy I am so thrilled I found your blog, I really
    found you by accident, while I was looking on Digg for something else, Anyhow I am
    here now and would just like to say cheers for a marvelous post and
    a all round interesting blog (I also love the
    theme/design), I don’t have time to read it all at the moment but
    I have bookmarked it and also included your RSS feeds, so when I have time I will be back to read much more, Please
    do keep up the fantastic work.

Leave a Reply

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