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

33 thoughts 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.

  2. After study some of the blog posts for your site now, and i genuinely like your strategy for blogging. I bookmarked it to my bookmark internet site list and will also be checking back soon. Pls check out my website also and inform me what you believe.

  3. I’m impressed, I have to admit. Truly rarely do I encounter a weblog that’s both educative and entertaining, and let me tell you, you could have hit the nail about the head. Your idea is outstanding; ab muscles an element that inadequate people are speaking intelligently about. We are delighted i came across this inside my look for something regarding this.

  4. I precisely desired to say thanks again. I am not sure what I could possibly have tried in the absence of those ideas contributed by you relating to such a topic. It had become a distressing condition in my view, however , being able to view the well-written tactic you processed it made me to weep over joy. Extremely grateful for your guidance and believe you realize what an amazing job you’re doing instructing others with the aid of a web site. Most likely you haven’t come across any of us.

  5. I’d been just browsing every now and then but happened to be to learn to read this post. I must say that i’m within the hand of luck today in any other case getting such an excellent post to learn to read wouldn’t are actually achievable personally, no less than. Really appreciate your articles.

  6. Someone essentially assist to make critically posts I’d state. This is the very first time I frequented your website page and to this point? I surprised with the analysis you made to create this actual submit incredible. Wonderful process!

  7. An intriguing discussion will probably be worth comment. I think that you simply write much more about this topic, it might become a taboo subject but generally consumers are inadequate to communicate in on such topics. To another. Cheers

  8. Youre so cool! I dont suppose Ive learn something like this before. So good to seek out anyone with some authentic ideas on this subject. realy thanks for beginning this up. this website is one thing that is wanted on the internet, someone with slightly originality. useful job for bringing one thing new to the web!

  9. Thank you for sharing excellent informations. Your web-site is so cool. I am impressed by the details that you’ve on this web site. It reveals how nicely you perceive this subject. Bookmarked this web page, will come back for more articles. You, my pal, ROCK! I found just the information I already searched all over the place and simply couldn’t come across. What an ideal web-site.

  10. Thanx for the effort, keep up the good work Great work, I am going to start a small Blog Engine course work using your site I hope you enjoy blogging with the popular BlogEngine.net.Thethoughts you express are really awesome. Hope you will right some more posts.

  11. Great – I should definitely pronounce, impressed with your web site. I had no trouble navigating through all tabs as well as related information ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Reasonably unusual. Is likely to appreciate it for those who add forums or anything, web site theme . a tones way for your customer to communicate. Excellent task..

  12. Hello! I’ve been reading your website for a long time now and finally got the courage to go ahead and give you a shout out from Huffman Texas! Just wanted to mention keep up the excellent job!

  13. The very crux of your writing whilst appearing reasonable at first, did not really sit properly with me personally after some time. Somewhere within the paragraphs you were able to make me a believer but only for a very short while. I however have a problem with your leaps in assumptions and you might do well to fill in all those breaks. In the event you actually can accomplish that, I could surely be impressed.

  14. I will right away clutch your rss as I can’t in finding your e-mail subscription link or e-newsletter service. Do you’ve any? Please let me understand in order that I could subscribe. Thanks.

Leave a Reply

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