有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中的排序数组

如果我使用基于元素的条件对Java数组进行排序,会发生什么

Point[] points = new Point[10];
Arrays.sort(temp, points[0].SLOPE_ORDER);

这是一个递归调用吗

斜率是一个比较器:

public final Comparator<Point> SLOPE_ORDER = new SlopeOrder();       // YOUR DEFINITION HERE

private class SlopeOrder implements Comparator<Point>
{
    public int compare(Point p1, Point p2)
    {
         ...
    }
}

共 (2) 个答案

  1. # 1 楼答案

    请看这里:

    Arrays.sort

    Implementation note: This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons. Temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays.

    所以答案是:不,它不是递归的

  2. # 2 楼答案

    根据Array#sort的命名约定和契约判断,SLOPE_ORDER是您正在使用的Point类的static final成员。具体来说,它是一个比较器,可以传递给sort方法

    为了回答你的问题,没有什么有趣的事情发生

    Arrays.sort(temp, points[0].SLOPE_ORDER);

    将计算points[0].SLOPE_ORDER作为对象的引用,并使用其值作为参数来执行排序,而无需再次查看points[0](至少不是为了获取SLOPE_ORDER

    如果SLOPE_ORDER同时是staticfinal,则可以用

    Arrays.sort(temp, Point.SLOPE_ORDER);

    结果将完全相同,代码更容易理解