2016-07-25 122 views
1

我有這樣的代碼,我使用的算法我在維基百科上找到寫道:鑑於此輸入快速排序算法不排序最終元素?

public static void quicksort(int[] arr, int low, int hi) 
    { 
     if(low < hi) 
     { 
      int pivot = part(arr, low, hi); 
      quicksort(arr, low, pivot - 1); 
      quicksort(arr, pivot + 1, hi); 
     } 
    } 
    public static int part(int[] arr, int low, int hi) 
    { 
     int pivot = arr[hi]; 

     int i = low; 
     for(int j = low; j < hi - 1; j++) 
     { 
      if(arr[j] <= pivot) 
      { 
       swap(arr, i, j); 
       i++; 
      } 
     } 
     swap(arr, i, hi); 
     return i; 
    } 

    public static void swap(int[] ar, int a, int b) 
    { 
     int temp = ar[a]; 
     ar[a] = ar[b]; 
     ar[b] = temp; 
    } 

31, 5, 5, 5, 5, 4, 4, 4, 5, 4 

,不要指望得到:

4, 4, 4, 4, 5, 5, 5, 5, 5, 31 

而是我得到:

4, 4, 4, 4, 5, 5, 5, 5, 31, 5 

什麼給?

我打電話與初始排序:quicksort(array, 0, array.Length - 1);

+1

考慮嘗試'快速排序(數組,0,array.Length)' –

+0

當我這樣做時,超出數組的邊界。零索引意味着較高的索引比長度小一個。 –

回答

2

如果你把它用Length - 1,那麼這個循環:

for (int j = low; j < hi - 1; j++) 

..should是:

for (int j = low; j <= hi ; j++) 
+1

修復它。謝謝。我只需要第二組眼睛就可以看到它,因爲我看不到那個錯誤。我會盡快接受,但現在不會讓我。 –