如何将选择排序转换为Comparator接口?

时间:2014-02-15 20:51:17

标签: java sorting comparator selection-sort

以下是选择排序功能的代码:

public class Selection
{
    public static void sort (Comparable [] a)
    { //Sort [] into increasing order.
        int N = a.length;
        for (int i = 0; i < N; i++)
        {    //Exchange a[i] with the smallest entry in a[i+1...N).
             int min = i;
             for (int j = i+1; j < N; j++)
                if (less (a[j], a[min]) ) min = j;
             exch(a, i, min); // assume exch has been implemented already
        }
    }
}

我被告知要在排序实现中支持比较器,我所要做的只是使用“Object”而不是“Comparable”,并将“Comparator”传递给“sort()”和“less()”并且在“less”中使用它。 这是在比较器界面中制作它的正确方法吗? :

public class Selection
{
    public static void sort (Object [] a, Comparator c)
    { //Sort [] into increasing order.
        int N = a.length;
        for (int i = 0; i < N; i++)
        {    //Exchange a[i] with the smallest entry in a[i+1...N).
             int min = i;
             for (int j = i+1; j < N; j++)
                if (less (c, a[j], a[min]) ) min = j;
             exch(a, i, min); 
        }
    }
}

private static booloean less (Comparator c, Object v, Object w)
{
    return c.compare(v, w) < 0; 
}

private static void exch (Object [] a, int i, int j)
{
    Object swap = a[i]; a[i] = a[j]; a[j] = swap; 
}

1 个答案:

答案 0 :(得分:0)

你所做的确实是一种推广算法的方法,因此它不仅适用于Comparable个对象,而且适用于任意对象,使用Comparator。代码存在一些问题(例如,使用原始类型的事实),但您的更改可以描述为&#34;实现所需目标所需的最小修改&#34 34。