Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaSort an Array in Java using Comparator

Sort an Array in Java using Comparator

A Comparator is an object that can be used to compare two objects and determine their order. You can use a Comparator to sort a list of objects in any order you choose, not just in ascending order.

Examples:

Array(Ascending Order):
    Input: arr = (4, 2, 5, 1, 3)
    Output: [1, 2, 3, 4, 5]
 
Array(Descending Order):
    Input: arr = (4, 2, 5, 1, 3)
    Output: [5, 4, 3, 2, 1]
 
Strings(Ascending Order):
    Input: str = ("Jan", "Tommy", "Jo", "Adam")
    Output: [Jo, Jan, Adam, Tommy]
 
Strings(Ascending Order):
    Input: str = ("Jan", "Tommy", "Jo", "Adam")
    Output: [Tommy, Adam, Jan, Jo]

Algorithm:

  1. Implement the Comparator interface and override the compare method.
  2. In the compare method, compare the two objects and return a negative integer if the first object is less than the second, a positive integer if the first object is greater than the second, or 0 if they are equal.
  3. To sort a list using the comparator, call the sort method on the list and pass an instance of the comparator as an argument.

Below are the implementations of the above algorithm for string and integers (Ascending and Descending both).

For Array (Ascending Order):

Java




// Java program to sort list of integers
// using Comparator in Java
// Ascending Order according to length
 
import java.util.Comparator;
import java.util.List;
import java.util.Arrays;
 
public class IntegerAscendingComparator implements Comparator<Integer> {
   
    @Override
    public int compare(Integer i1, Integer i2) {
        return i1 - i2;
    }
       
    public static void main (String[] args) {
          List<Integer> numbers = Arrays.asList(4, 2, 5, 1, 3);
        numbers.sort(new IntegerAscendingComparator());
        System.out.println(numbers); // [1, 2, 3, 4, 5]
    }
}
 
// This code is contributed by Susobhan Akhuli


Output

[1, 2, 3, 4, 5]

For Array (Descending Order):

Java




// Java program to sort list of integers
// using Comparator in Java
// Descending Order according to length
 
import java.util.Comparator;
import java.util.List;
import java.util.Arrays;
 
public class IntegerDescendingComparator implements Comparator<Integer> {
   
    @Override
    public int compare(Integer i1, Integer i2) {
        return i2 - i1;
    }
       
    public static void main (String[] args) {
          List<Integer> numbers = Arrays.asList(4, 2, 5, 1, 3);
        numbers.sort(new IntegerDescendingComparator());
        System.out.println(numbers); // [5, 4, 3, 2, 1]
    }
}
 
// This code is contributed by Susobhan Akhuli


Output

[5, 4, 3, 2, 1]

For Strings (Ascending Order):

Java




// Java program to sort list of strings
// using Comparator in Java
// Ascending Order according to length
 
import java.util.Comparator;
import java.util.List;
import java.util.Arrays;
 
public class StringLengthComparator implements Comparator<String> {
   
    @Override
    public int compare(String s1, String s2) {
        return s1.length() - s2.length();
    }
       
    public static void main (String[] args) {
          List<String> names = Arrays.asList("Jan", "Tommy", "Jo", "Adam");
        names.sort(new StringLengthComparator());
        System.out.println(names); // [Jo, Jan, Adam, Tommy]
    }
}
 
// This code is contributed by Susobhan Akhuli


Output

[Jo, Jan, Adam, Tommy]

For Strings (Descending Order):

Java




// Java program to sort list of strings
// using Comparator in Java
// Descending Order according to length
 
import java.util.Comparator;
import java.util.List;
import java.util.Arrays;
 
public class StringLengthComparator implements Comparator<String> {
   
    @Override
    public int compare(String s1, String s2) {
        return s2.length() - s1.length();
    }
       
    public static void main (String[] args) {
          List<String> names = Arrays.asList("Jan", "Tommy", "Jo", "Adam");
        names.sort(new StringLengthComparator());
        System.out.println(names); // [Tommy, Adam, Jan, Jo]
    }
}
 
// This code is contributed by Susobhan Akhuli


Output

[Tommy, Adam, Jan, Jo]

Complexities:

  • Time Complexity: O(n log(n))
  • Auxiliary Space: O(1)

Explanation

The comparator that we provided has a time complexity of O(n log(n)), where n is the number of elements in the list. This is because the sort method uses a comparison-based algorithm (such as merge sort or quick sort) to sort the list, and the time complexity of these algorithms is O(n * log(n)). The space complexity of the comparator is O(1) since it does not allocate any additional memory beyond the comparator object itself.

RELATED ARTICLES

Most Popular

Recent Comments