Java中的CompareTo()方法

时间:2014-04-16 20:43:38

标签: java

//我知道compareTo()返回一个int值。

 returns 0 if a equal b
 returns -1 if a < b
 returns 1 if a > b

//但是sort方法如何利用这些0,1,-1值,以及它如何精确地排列列表。

2 个答案:

答案 0 :(得分:1)

使用compareTo(),

对数组进行排序
public void sort(Comparable[] lst)
{
    for(int i=0; i<lst.length; i++)
    {
        for(int j=i; j<lst.length; j++)
        {
            if(lst[i].compareTo(lst[j]) < 0)
            {
                //swap elements, sorts in ascending order
                Comparable tmp = lst[i];
                lst[i] = lst[j];
                lst[j] = tmp;
            }
        }
    }
}

答案 1 :(得分:-1)

好吧,here's the code,不确定你还想要什么。 Collections.sort似乎最终称之为。

private static <T> void binarySort(T[] a, int lo, int hi, int start, Comparator<? super T> c) {
    assert lo <= start && start <= hi;
    if (start == lo)
        start++;
    for ( ; start < hi; start++) {
        T pivot = a[start];
        // Set left (and right) to the index where a[start] (pivot) belongs
        int left = lo;
        int right = start;
        assert left <= right;
        /*
         * Invariants:
         *   pivot >= all in [lo, left).
         *   pivot <  all in [right, start).
         */
        while (left < right) {
            int mid = (left + right) >>> 1;
            if (c.compare(pivot, a[mid]) < 0)
                right = mid;
            else
                left = mid + 1;
        }
        assert left == right;
        /*
         * The invariants still hold: pivot >= all in [lo, left) and
         * pivot < all in [left, start), so pivot belongs at left.  Note
         * that if there are elements equal to pivot, left points to the
         * first slot after them -- that's why this sort is stable.
         * Slide elements over to make room for pivot.
         */
        int n = start - left;  // The number of elements to move
        // Switch is just an optimization for arraycopy in default case
        switch (n) {
            case 2:  a[left + 2] = a[left + 1];
            case 1:  a[left + 1] = a[left];
                     break;
            default: System.arraycopy(a, left, a, left + 1, n);
        }
        a[left] = pivot;
    }
}