Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Comparator parameter in main method

I am implementing insertion sort method. Here is the requirement of my code.

  1. The method insertionSort is a static method that returns nothing.
  2. It has two parameters: a generic array and a Comparator (generic).
  3. It sorts the generic array using the merge sort algorithms

My Question is: What do I use for Comparator parameter c when calling in main method?

Here is what I have so far, I have some unimplemented method (merge sort an isAnagaram) ignore those

public class Sorting
{
    public static <T extends Comparable<T>> void insertionSort(T[] a, Comparator<T> c)
    {
        for (int i = 0; i < a.length; i++)
        {
            T key = a[i];
            int j;
            for (j = i - 1; j >= 0; j--)
            {
                if (c.compare(a[j], key) <= 0)
                    break;
                a[j + 1] = a[j];
            }

            a[j + 1] = key;
        }
    }

    public static void mergeSort()
    {
        //TODO
    }

    public static boolean isAnagram(String first, String second)
    {
        //TODO
        return false;
    }

    public static void main(String[] args)
    {
        Integer a[] = { 99, 8, 19, 88, 62, 2, 1, 9, 19 };

        // not sure how to pass parameter comparator

        insertionSort(a, null );

        for (int i = 0; i < a.length; i++)
        {
            System.out.print(a[i] + " ");
        }
    }
}

I looked around on stack overflow as well as googled a lot on a Comparator interface but I couldn't really find any method where you are required to pass Generic comparator as parameter. Can someone help me tell what I am not understanding or direct me to right direction.

like image 258
dgl Avatar asked Oct 27 '25 23:10

dgl


1 Answers

Comparator is an interface, which can not be instantiated. You need to implement it. There are two methods to implement:

  • compare
  • equals

You need to implement them for Integer elements. Like this:

public class IntegerComparator implements Comparator {

    public int compare(Integer a, Integer b) {
        return a.intValue() - b.intValue();
    }

    public int equals(Object obj) {
        return this.equals(obj);
    }

}

and in your main you call it like this:

insertionSort(a, new IntegerComparator );

Explanation: Comparator is an interface, therefore it cannot be instantiated. You need to implement it. You have an array of Integer elements to sort, therefore you can implement an Integer Comparator. The compare method returns the subtraction of the int values. If a < b, then it is negative. If a == b, then it is 0. If a > b, then it is positive.

Read more here and here.

like image 167
Lajos Arpad Avatar answered Oct 30 '25 15:10

Lajos Arpad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!