2016-11-07 62 views
0

出於某種原因,我的數組的中間元素仍然無序......我不知道爲什麼,但我只是中間元素仍然未排序

public class QuickSort { 

    public int a[]; 

    public QuickSort(int[] a) { 
     this.a = a; 
    } 

    private void swap(int pos1, int pos2) { 
     int t = a[pos1]; 
     a[pos1] = a[pos2]; 
     a[pos2] = t; 
    } 

    private int partition(int low, int high) { 
     int i = low, j = low + 1, pivot = low; 
     while (j < high) { 
      if (a[j] <= a[pivot]) { 
       swap(++i, j); 
      } 
      j++; 
     } 
     swap(i, pivot); 
     return i; 
    } 

    private void sort(int low, int high) { 
     int i; 
     if (low >= high) 
      return; 
     else { 
      i = partition(low, high); 
      sort(i + 1, high); 
      sort(low, i - 1); 
     } 
    } 

    public String toString() { 
     StringBuilder sb = new StringBuilder(""); 
     for (int i : a) { 
      sb.append(i); 
      sb.append("\n"); 
     } 

     return sb.toString(); 
    } 

    private static int[] generateRandomNumbers(int s) { 

     int a[] = new int[s]; 

     for (int i = 0; i < s; i++) { 
      a[i] = new Random().nextInt(50); 
     } 

     return a; 
    } 

    public static void main(String args[]) { 

     Scanner sc = new Scanner(System.in); 
     System.out.println("Enter the size of elements"); 
     int s = sc.nextInt(); 

     QuickSort obj = new QuickSort(generateRandomNumbers(s)); 

     System.out.println(obj.toString()); 

     obj.sort(0, s - 1); 

     System.out.println("\n"); 
     System.out.println(obj.toString()); 
    } 

} 

數組充滿了隨機生成的數字,這是一個標準的快速排序算法 任何幫助,將不勝感激,我是一個新手程序員,試圖調試的時間太長了這段代碼...

+1

你可以給你使用這個與和O的一個數組的例子本安輸出? –

+0

我隨機生成數組...... ill編輯我的問題以添加整個代碼... –

+0

您的支點是第一個元素。它不應該在中間更多嗎? – TedTrippin

回答

0

修改

swap(i+1, pivot); 
return i+1; 

int i = low-1, j = low, pivot = high; 

if (low < high) 
     { 
      i = partition(low, high); 
      sort(i + 1, high); 
      sort(low, i - 1); 
     } 

這些更改後完美的作品。

+0

謝謝...對不起,我的聲譽太低... –

+0

沒問題總是樂意幫助新手程序員喜歡我的自我。如果解決了您的問題,請將其標記爲答案 – Arthas

0

或者只是改變了「<」到「< =」作爲其不檢查高元......

while (j <= high) { 
+0

謝謝!我無法相信自己犯了這樣一個愚蠢的錯誤......對不起來,我的聲望太低了...... –

0

,我發現我的錯誤.... 它應該是

while (j <= high) 

代替

(j < high) 
相關問題