JavaDevNotes.com

Java Sort Array Examples

An array is a common data structure in many languages. It is simple and easy to understand, hence it is commonly used in many situations. However, it is very common requirement to sort a an array or a collection of objects to ensure elements are in specific order (E.g. increasing order of value). If you need to learn how to perform this operation, below are some examples on how to Sort an Array in Java.

Sort Array Using Arrays.sort()

The utility class java.util.Arrays has overloaded method function sort() to help sort different types of arrays. Here is one signature:
static void sort(int[] a);
The function does not return anything (void) and it sorts the array parameter. When you invoke this method, the array you passed will be modified and no new array is created. Note also the above is just one sample syntax, the method can accept different types of arrays. Here is an example code that uses this:
int[] myArray = { 5, 2, 7, 3, 9 };
Arrays.sort(myArray);
System.out.println(Arrays.toString(myArray));

We created an array of integers in no particular order. The call to Arrays.sort sorts the parameter myArray. Below is the output of the code:

[2, 3, 5, 7, 9]

Here are examples of how to sort different arrays of primitive type.

  • Sort Array of byte
    byte[] myArray = { 125, 112, 127, 13, 19 };
    Arrays.sort(myArray);
    
  • Sort Array of char
    char[] myArray = { 'x', 'a', 'm', 'c', 'z' };
    Arrays.sort(myArray);
    
  • Sort Array of short
    short[] myArray = { 515, 122, 700, 301, 129 };
    Arrays.sort(myArray);
    
  • Sort Array of int
    int[] myArray = { 5, 2, 7, 3, 9 };
    Arrays.sort(myArray);
    
  • Sort Array of long
    long[] myArray = { 12885, 3213122, 567546457, 36465, 94234236 };
    Arrays.sort(myArray);
    
  • Sort Array of float
    float[] myArray = { 12.5f, 20.50f, 71.35f, 39.5f, 900.11f };
    Arrays.sort(myArray);
    
  • Sort Array of double
    double[] myArray = { 21.45d, 120.65d, 710.25d, 930.15d, 190.75d };
    Arrays.sort(myArray);
    

Sort Portion of Array Using Arrays.sort()

It is possible to sort only a portion or subset of an Array using Arrays.sort(). The start and end index of the items that needed to be sorted should be specified. Here is a syntax:
static void sort(int[] a, int fromIndex, int toIndex)
The fromIndex parameter is the index of the first element to be sorted (inclusive) and the toIndex parameter is the index of the last element to be sorted (exclusive). Here is example usage:
int[] myArray = { 5, 2, 7, 3, 9, 1, 4, 11 };
Arrays.sort(myArray, 2, 6);
System.out.println(Arrays.toString(myArray));
The fromIndex parameter is 2, which is the third element of the array with value 7. The toIndex parameter is 6, which is the seventh element of the array with value 4. This means all elements from the third element (value 7), upto the sixth element (before the value 4, which should be the value 1) will be sorted. The result output is below:
[5, 2, 1, 3, 7, 9, 4, 11]
Notice that items in Index 0, 1, 6 and 7 are untouched. Only items from index 2 up to index 5 are sorted.

Sort Array of Objects Using Arrays.sort()

The Arrays.sort() is not limited to sorting arrays of primitives. It can also be used to sort Arrays of Objects. Here is the syntax:

static void sort(Object[] a)

It is possible to sort any array of objects. Here is an example of sorting an Array of String:
String[] myArray = { "Corn", "Banana", "Apple", "Orange" };
Arrays.sort(myArray);
System.out.println(Arrays.toString(myArray));
And the output is as expected:
[Apple, Banana, Corn, Orange]

Sort Array of Custom Class Using Arrays.sort()

If we have our own custom class, we can use Arrays.sort() to sort an array of instances of the said class. But there is a catch. Consider the code below:

import java.util.Arrays;
public class Test {
   public static void main(String[] args) {
      Person[] myArray = new Person[5];
      myArray[0] = new Person("John", 5);
      myArray[1] = new Person("Peter", 2);
      myArray[2] = new Person("Anthony", 15);
      myArray[3] = new Person("Sally", 8);
      myArray[4] = new Person("Cory", 7);
      Arrays.sort(myArray);
      System.out.println(Arrays.toString(myArray));
   }
}
public class Person {
   String name;
   int age;
   public Person(String name, int age) {
      this.name = name;
      this.age = age;
   }
}

The code above defines a class Person and creates an array of it's instances. The code above will compile, the output when run however will be:

Exception in thread "main" java.lang.ClassCastException: Person cannot be cast to java.lang.Comparable
	at java.util.Arrays.mergeSort(Arrays.java:1157)
	at java.util.Arrays.sort(Arrays.java:1092)
	at Test.main(Test.java:10)

A ClassCastException is thrown because the utility method does not know how to compare values of type Person. To make this work, the Person class must implement the Comparable interface. Here is the modified example that works:
import java.util.Arrays;
public class Test {
   public static void main(String[] args) {
      Person[] myArray = new Person[5];
      myArray[0] = new Person("John", 5);
      myArray[1] = new Person("Peter", 2);
      myArray[2] = new Person("Anthony", 15);
      myArray[3] = new Person("Sally", 8);
      myArray[4] = new Person("Cory", 7);
      Arrays.sort(myArray);
      System.out.println(Arrays.toString(myArray));
   }
}
public class Person implements Comparable<Person> {
   String name;
   int age;
   public Person(String name, int age) {
      this.name = name;
      this.age = age;
   }
   public String toString() {
      return "[name: " + name + ", age: " + age + "]";
   }
   @Override
   public int compareTo(Person o) {
      return Integer.valueOf(age).compareTo(o.age);
   }
}
The Person above implemented the Comparable interface and used the age of the Person as the criteria for comparison. The effect is that when we invoke Arrays.sort(), the array will be sorted according to the age of Persons. The expected output therefore is shown below:
[[name: Peter, age: 2], [name: John, age: 5], [name: Cory, age: 7], [name: Sally, age: 8], [name: Anthony, age: 15]]

Sort Array of Custom Class Using Arrays.sort() and Custom Comparator

There is a drawback when we rely on the compareTo method as shown in the example above. We are stuck into one implementation or logic. What if we wish to sort an array of Person by age in one scenario, and we wish to sort again by name on another scenario? The solution is to use a Comparator. Here is the syntax:
public static <T> void sort(T[] a, Comparator<? super T> c)
The parameter comparator holds the logic on how to compare objects. So to have different behaviors, we can pass different Comparators depending on what we need. Here is an example code:
import java.util.Arrays;
public class Test {
   public static void main(String[] args) {
      Person[] myArray = new Person[5];
      myArray[0] = new Person("John", 5);
      myArray[1] = new Person("Peter", 2);
      myArray[2] = new Person("Anthony", 15);
      myArray[3] = new Person("Sally", 8);
      myArray[4] = new Person("Cory", 7);
      Arrays.sort(myArray, Person.NAME_COMPARATOR);
      System.out.println(Arrays.toString(myArray));
      Arrays.sort(myArray, Person.AGE_COMPARATOR);
      System.out.println(Arrays.toString(myArray));
   }
}
import java.util.Comparator;
public class Person {
   public static Comparator<Person> AGE_COMPARATOR = new Comparator<Person>() {
      @Override
      public int compare(final Person o1, final Person o2) {
         return Integer.valueOf(o1.age).compareTo(o2.age);
      }
   };
   public static Comparator<Person> NAME_COMPARATOR = new Comparator<Person>() {
      @Override
      public int compare(final Person o1, final Person o2) {
         return o1.name.compareTo(o2.name);
      }
   };
   String name;
   int age;
   public Person(String name, int age) {
      this.name = name;
      this.age = age;
   }
   public String toString() {
      return "[name: " + name + ", age: " + age + "]";
   }
}
In the example above, notice that we don't need to implement Comparable anymore since we are using Comparators. Two comparators are created, one sorts by name (NAME_COMPARATOR) while the other sorts by age (AGE_COMPARATOR). The array is sorted by using both comparators. Here is the result of the code above when run:
[[name: Anthony, age: 15], [name: Cory, age: 7], [name: John, age: 5], [name: Peter, age: 2], [name: Sally, age: 8]]
[[name: Peter, age: 2], [name: John, age: 5], [name: Cory, age: 7], [name: Sally, age: 8], [name: Anthony, age: 15]]
The first line displayed the list of Person sorted by name and the second line displayed the list of Person sorted by age.

Sort Array In Descending Order Using Arrays.sort()

By deault, Arrays.sort() sorts an array in ascending order. But what if we need to sort in descending order? One trick is to reverse the result after sorting in ascending order.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Test {
   public static void main(String[] args) {
      Integer[] myArray = { 5, 2, 7, 3, 9 };
      Arrays.sort(myArray);
      List<Integer> myList = Arrays.asList(myArray);
      Collections.reverse(myList);
      myList.toArray(myArray);
      System.out.println(Arrays.toString(myArray));
   }
}
The above code uses a List to be able to reverse the items in the Array. The output is shown below:
[9, 7, 5, 3, 2]

Another way to achieve sorting array in descending order is to use a custom Comparator that reverses the logic of comparing. Here is an example:

import java.util.Arrays;
import java.util.Comparator;
public class Test {
   public static void main(String[] args) {
      Integer[] myArray = { 5, 2, 7, 3, 9 };
      Arrays.sort(myArray, new Comparator<Integer>(){
         @Override
         public int compare(Integer arg0, Integer arg1) {
            return -1 * arg0.compareTo(arg1);
         }});
      System.out.println(Arrays.toString(myArray));
   }
}

Notice that by multiplying the result of compareTo with -1, the logic is reversed. Hence the output of the code above will sort the array of Integers in descending order.

Sort Array Using Custom Logic

If you are the type of programmer who wish to use your own implementation, here is an example code that will sort an array without invoking any ready made methods:
import java.util.Arrays;
public class Test {
   public static void bubbleSort(Integer[] arr) {
      int j = 0;
      Integer tmp;
      boolean sorted = false;
      while (!sorted) {
         sorted = true;
         j++;
         for (int i = 0; i < arr.length - j; i++) {
            if (arr[i].compareTo(arr[i + 1]) > 0) {
               tmp = arr[i];
               arr[i] = arr[i + 1];
               arr[i + 1] = tmp;
               sorted = false;
            }
         }
      }
   }
   public static void main(String[] args) {
      Integer[] myArray = { 5, 2, 7, 3, 9 };
      bubbleSort(myArray);
      System.out.println(Arrays.toString(myArray));
   }
}
The code uses the bubble sort algorithm.