2014-04-16 145 views
-5

//我知道compareTo()返回一個int值。Java中的CompareTo()方法

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

//但排序方法如何利用這些0,1,-1值,以及它如何精確排列列表。

+2

它交換元件。 –

+1

它不需要總是返回這些值(-1和1)。例如,''a「.compareTo(」d「)== -3'。 _「是一個負整數,零或正整數,因爲該對象小於,等於或大於指定的對象。」_ –

+0

如果compareTo(e1,e2)<0,則e1應位於e2的左側 – Arkadiy

回答

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

那麼,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; 
    } 
} 
+0

如果DV是由於格式問題,這些問題已得到解決。否則請解釋。 – djechlin

+0

由於compareTo方法在Comparable接口中,這是我在我的類中實現的,所以它基於Comparator接口顯示它,是否也適用於可比接口。 – Aamir

+0

@Aamir瀏覽源代碼並看看。 – djechlin