Sort an Array using Comparator

Sort an Array using Comparator

Comparator is an interface which comes under java.util package is useful to impose a total ordering on a collection of elements (Objects) of an array into ascending or descending order.

interface Comparator<T>

Where T represents the type of elements (Objects) compared by the Comparator.

The Comparator interface contains a method compare() that should be implemented in such a way that the two object should be compared using comparedTo() method as –

public int compare(Integer x, Integer y){
     return x.compareTo(y);
}

The compareTo() method returns a postive value if  x>y and a negative value if x<y whereas it returns 0(zero) if x==y (double equal sign). This logic can be applied to a group of objects when we want to arrange them in ascending/descending order.

Let have example that shows sorting using comparator

package com.c2s.collection;

import java.util.Comparator;

public class AscendingSort implements Comparator<Integer>{

	@Override
	public int compare(Integer x, Integer y) {
		// TODO Auto-generated method stub
		return x.compareTo(y);
	}
}
package com.c2s.collection;

import java.util.Comparator;

public class DescendingSort implements Comparator<Integer> {

	@Override
	public int compare(Integer x, Integer y) {
		// TODO Auto-generated method stub
		return y.compareTo(x);
	}
}

 

Test Class

package com.c2s.collection;

import java.util.Arrays;

public class SortArray {

	public static void main(String args[]){

		Integer intArray[] = new Integer[5];
		intArray[0] = 10;
		intArray[1] = 55;
		intArray[2] = 22;
		intArray[3] = 10;
		intArray[4] = 15;

		//Sort - Ascending order
		Arrays.sort(intArray, new AscendingSort());

		//Print Ascending order
		System.out.println("Sorted in Ascending order: ");
		display(intArray);

		//Sort - Descending order
		Arrays.sort(intArray, new DescendingSort());

		//Print Descending order
		System.out.println("\n\nSorted in Descending order: ");
		display(intArray);
	}
	
	public static void display(Integer arr[]){
		for(Integer i:arr){
			System.out.print(i+"\t");
		}
		
	}
}

 

Output:

Sorted in Ascending order: 
10	10	15	22	55	

Sorted in Descending order: 
55	22	15	10	10

 

Stay tuned for more updates !

Leave a Reply

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