Dzung Nguyen
Dzung Nguyen

Reputation: 3944

Sort array in Java

What happened if I sort a Java array with criteria based on its element?

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

Will this be a recursive call?

SLOPE_ORDER is a comparator:

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

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

Upvotes: 1

Views: 210

Answers (2)

toniedzwiedz
toniedzwiedz

Reputation: 18543

Judging by the naming convention and the contract of Array#sort, SLOPE_ORDER is a static final member of the Point class that you are using. Specifically, it's a comparator that can be passed to the sort method.

To answer your question, nothing interesting will happen.

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

will evaluate points[0].SLOPE_ORDER as the reference to the object and use its value as an argument to perform the sorting without needing to look at points[0] ever again (at least not in order to get SLOPE_ORDER.

If SLOPE_ORDER is both static and final, this can be replaced with

Arrays.sort(temp, Point.SLOPE_ORDER);

the result will be exactly the same and the code is much easier to understand.

Upvotes: 1

peter.petrov
peter.petrov

Reputation: 39437

See here:

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.

So the answer is: no, it's not recursive.

Upvotes: 4

Related Questions