Arrays.sort() in java

Let’s learn Arrays.sort() in java.

Arrays.sort() in java

sort() method is in java.util.Arrays class. sort() method sorts the specified range of the array into ascending order.

The range to be sorted extends from the index fromIndex, inclusive, to the index toIndex, exclusive.

If fromIndex == toIndex, the range to be sorted is empty.

Syntax:

public static void sort(int[] a, int fromIndex, int toIndex)

Parameters:

a – array to be sorted

fromIndex – index of the first element to be sorted, inclusive.

toIndex – index of the last element to be sorted, exclusive.

sort() method do not return any value.

Throws:

IllegalArgumentException – if fromIndex > toIndex

ArrayIndexOutOfBoundsException – if fromIndex < 0 or toIndex > arr.length


Here’s example on arrays.sort() in java. sort array in ascending order java.

import java.util.Arrays;
public class ArraysSortExample
{
   public static void main(String[] args)
   {
      int[] arrNum = {14, 5, 8, 23, 100, 85};
      // arrays.sort
      // arrays.sort method by default sorts in ascending order
      Arrays.sort(arrNum);
      System.out.println(Arrays.toString(arrNum));
   }
}


Output:

[5, 8, 14, 23, 85, 100]


Now let’s learn how to sort a subarray of an array using Arrays.sort() method.

import java.util.Arrays;
public class SortSubarray
{
   public static void main(String[] args)
   {
      int[] arrDemo = {14, 8, 5, 54, 41, 10, 1, 500};
      // here we are sorting subarray elements only i.e, {8, 5, 54, 41}
      // arrays.sort
      Arrays.sort(arrDemo, 1, 5);
      System.out.println(Arrays.toString(arrDemo));
   }
}


Output:

[14, 5, 8, 41, 54, 10, 1, 500]


Similarly let’s see java program to sort array in descending order or java sort array descending.

To sort array in descending order we need to provide external comparator which sorts array elements in reverse order.

Also read – sparse matrix and its representations in java

In java we have built-in method reverseOrder() of Collections class.

This method returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

import java.util.Arrays;
import java.util.Collections;
public class ArraySortDescending
{
   public static void main(String[] args)
   {
      Integer[] arrNum = {14, 8, 5, 54, 41, 10, 1, 500};
      // sort descending order
      // arrays.sort
      Arrays.sort(arrNum, Collections.reverseOrder());
      System.out.println(Arrays.toString(arrNum));
   }
}


Output:

[500, 54, 41, 14, 10, 8, 5, 1]


Sort string array in java

Arrays.sort() method sorts the specified array according to the natural ordering of its elements.

Here’s the java program to sort strings in an alphabetical order.

import java.util.Arrays;
public class SortStringAlphabeticalOrder
{
   public static void main(String[] args)
   {
      String[] strAsc = {"Bear","Fox","Deer","Cheetah","Anteater","Elephant"};
      System.out.println("Before sorting: ");
      for(String string : strAsc)
      {
         System.out.println(string);
      }
      // arrays.sort
      Arrays.sort(strAsc);
      System.out.println("-----------------------------------");
      System.out.println("After sorting: ");
      for(String str : strAsc)
      {
         System.out.println(str);
      }
   }
}


Output:

arrays.sort() in java

Similarly we can sort above string array in reverse order using reverseOrder() method of Collections class.

reverseOrder() method sorts the array in reverse-lexicographic (alphabetical) order. The returned comparator is serializable.

Here’s the java program on how to sort an array of strings in descending or reverse order in java.

import java.util.Arrays;
import java.util.Collections;
public class SortStringAlphabeticalOrder 
{
   public static void main(String[] args) 
   {
      String[] strDesc = {"Bear","Fox","Deer","Cheetah","Anteater","Elephant"};
      System.out.println("Before sorting: ");
      for(String string : strDesc)
      {
         System.out.println(string);
      }
      // arrays.sort
      Arrays.sort(strDesc, Collections.reverseOrder());   
      System.out.println("-----------------------------------");
      System.out.println("Sorting string array in descending or reverse order: ");
      for(String string : strDesc)
      {
         System.out.println(string);
      }
   }
}


Output:

Before sorting:
Bear
Fox
Deer
Cheetah
Anteater

Elephant

Sorting string array in descending or reverse order:
Fox
Elephant
Deer
Cheetah
Bear
Anteater


arrays.sort comparator

In java.util.Arrays.sort method sorts the specified array of objects according to the order induced by the specified comparator.

Syntax:

public static <T> void sort(T[] a, Comparator<? super T> c)

Parameters:

T – the class of the objects to be sorted.

a – array to be sorted.

c – comparator to determine the order of the array.

A null value indicates that the elements’ natural ordering should be used.

Returns:

no value

Exceptions:

ClassCastException – if the array contains elements that are not mutually comparable using the specified comparator.

IllegalArgumentException – (optional) if the comparator isfound to violate the Comparator contract.

Let’s see an example,

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
public class ArraySortComparator 
{
   public static void main(String[] args) 
   {
      Short[] arrNumber = new Short[]{14, 8, 5, 54, 41};
      // print given array elements
      System.out.println("Given array: ");
      for(short num : arrNumber) 
      {
         System.out.println(num);
      }
      // creating comparator
      Comparator obj = Collections.reverseOrder();
      // sorting array in reverse order using comparator
      Arrays.sort(arrNumber, obj);
      // let us print all the elements available in list
      System.out.println("sorted values: ");
      for(short num : arrNumber) 
      {
         System.out.println(num);
      }
   }
}


Output:

Given array:
14
8
5
54
41
sorted values:
54
41
14
8
5


java sort arraylist

To sort an arraylist sort() method of Collections class is used.

This method sorts given list into ascending order, according to natural ordering of its elements.

All elements in the list must implement Comparable interface. Here’s an example.

import java.util.ArrayList;
import java.util.Collections;
public class JavaSortArraylist 
{
   public static void main(String[] args) 
   {
      ArrayList<String> al = new ArrayList<String>();
      al.add("Bear"); 
      al.add("Fox"); 
      al.add("Deer"); 
      al.add("Cheetah"); 
      al.add("Anteater");
      al.add("Elephant");
      System.out.println("Before sorting ArrayList: " + al);
      Collections.sort(al); 
      System.out.println("After sorting ArrayList in Ascending order: " + al);
   }
}


Output:

Before sorting ArrayList: [Bear, Fox, Deer, Cheetah, Anteater, Elephant]
After sorting ArrayList in Ascending order: [Anteater, Bear, Cheetah, Deer, Elephant, Fox]


java sort array of objects

To sort an array of objects using sort() method of Arrays class we have to implement Comparable interface.

class which implements Comparable interface must override compareTo() abstract method.

Also read – continue statement in java

This method compares object with specified object. Let’s see an example, where array object is ordered by age.

Here’s an example on java sort array of objects.

import java.util.Arrays;
public class Employee implements Comparable<Employee>
{
   private String empName; 
   private int empAge;
   public Employee(String name, int age) 
   { 
      this.empName = name; 
      this.empAge = age; 
   }
   @Override 
   public String toString() 
   { 
      return "{" + "name='" + empName + '\'' + ", age=" + empAge + '}'; 
   }
   public String getName() 
   { 
      return empName; 
   }
   public int getAge() 
   { 
      return empAge; 
   }
   @Override 
   public int compareTo(Employee o) 
   { 
      if(this.empAge != o.getAge()) 
      { 
         return this.empAge - o.getAge(); 
      }
      return this.empName.compareTo(o.getName()); 
   }
}
public class SortArrayObjects 
{
   public static void main(String[] args) 
   {
      Employee[] obj = { new Employee("virat", 25), new Employee("dhoni", 20), 
                         new Employee("rohit", 22), new Employee("rahul", 24)};
      Arrays.sort(obj); 
      System.out.println(Arrays.toString(obj));
   }
}


Output:

[{name=’dhoni’, age=20}, {name=’rohit’, age=22}, {name=’rahul’, age=24}, {name=’virat’, age=25}]

Now let’s see by implementing Comparator interface.

class which implements this interface should override compare() abstract method which compares two arguments for order.

A comparison function, which imposes a total ordering on some collection of objects.

Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order.

public class Employee
{
   private String empName; 
   private int empAge;
   public Employee(String name, int age) 
   { 
      this.empName = name; 
      this.empAge = age; 
   }
   @Override 
   public String toString() 
   { 
      return "{" + "name = '" + empName + '\'' + ", age = " + empAge + '}'; 
   }
   public String getName() 
   { 
      return empName; 
   }
   public int getAge() 
   { 
      return empAge; 
   }
}
import java.util.Arrays;
import java.util.Comparator;
public class SortArrayObjects 
{
   public static void main(String[] args) 
   {
      Employee[] obj = { new Employee("virat", 25), new Employee("dhoni", 20), 
                         new Employee("rohit", 22), new Employee("rahul", 24)};
      Arrays.sort(obj, new Comparator<Employee>() 
      { 
         @Override 
         public int compare(Employee first, Employee second) 
         { 
            if(first.getAge() != second.getAge()) 
            { 
               return first.getAge() - second.getAge(); 
            }
            return first.getName().compareTo(second.getName()); 
         }
      });
      System.out.println(Arrays.toString(obj));
   }
}


Output:

[{name = ‘dhoni’, age = 20}, {name = ‘rohit’, age = 22}, {name = ‘rahul’, age = 24}, {name = ‘virat’, age = 25}]


how to sort an array in java without using sort method

Let’s learn how to sort an array in java without using sort() method (descending order).

public class WithoutUsingSortMethod
{
   public static void main(String[] args) 
   {
      int temp;
      int[] arrNumbers = {14, 8, 5, 54, 41, 10, 1, 500};
      System.out.println("Before sort: ");
      for(int num : arrNumbers)
      {
         System.out.println(num);
      }
      for(int a = 0; a <= arrNumbers.length - 1; a++)
      {
         for(int b = 0; b <= arrNumbers.length - 2; b++)
         {
            if(arrNumbers[b] < arrNumbers[b + 1])
            {
               temp = arrNumbers[b];
               arrNumbers[b] = arrNumbers[b + 1];
               arrNumbers[b + 1] = temp;
            }
         }
      }
      System.out.println("---------------");
      System.out.println("After sort: ");
      for(int num : arrNumbers)  
      {
         System.out.println(num);
      }
   }
}


Output:

Before sort:
14
8
5
54
41
10
1

500

After sort:
500
54
41
14
10
8
5
1


Let’s learn how to sort an array in java without using sort() method (ascending order).

public class WithoutSortMethod
{
   public static void main(String[] args)
   {
      int temp;
      int[] arrNumbers = {14, 8, 5, 54, 41, 10, 1, 500};
      System.out.println("Before sort: ");
      for(int num : arrNumbers)
      {
         System.out.println(num);
      }
      for(int a = 0; a < arrNumbers.length; a++)
      {
         for(int b = a + 1; b < arrNumbers.length; b++)
         {
            if(arrNumbers[a] > arrNumbers[b])
            {
               temp = arrNumbers[a];
               arrNumbers[a] = arrNumbers[b];
               arrNumbers[b] = temp;
            }
         }
      }
      System.out.println("---------------");
      System.out.println("After sort: ");
      for(int num : arrNumbers)
      {
         System.out.println(num);
      }
   }
}


Output:

Before sort:
14
8
5
54
41
10
1

500

After sort:
1
5
8
10
14
41
54
500