2013-07-16 54 views
1

我寫了下面的快速排序算法,但它拋出了堆棧溢出異常。 關於如何解決此問題的任何建議..quicksort算法拋出stackoverflow異常錯誤

static void Main(string[] args) 
    { 
     int[] input={17,12,6,19,23,8,5,10}; 
     QuickSort(input,0,7); 
     foreach (int item in input) 
     { 
      Console.WriteLine(item); 
     } 
    } 
    static void QuickSort(int[] input,int p , int r) 
    { 
     if (p<r) 
     { 
      int q=Partition(input, p, r); 
      QuickSort(input, p, q); 
      QuickSort(input, q, r); 
     } 
    } 
    static int Partition(int [] input,int p,int r) 
    { 
     int pivot = input[r];//pivot element 
     int i = p - 1; 
     int j = r + 1; 
     while (true) 
     { 
      do 
      { 
       i = i + 1; 
      } while (!(input[i]>=pivot)); 
      do 
      { 
       j = j - 1; 
      } while (!(input[j] <= pivot)); 
      //swap 
      if (i<j) 
      { 
       int temp = input[i]; 
       input[i] = input[j]; 
       input[j] = temp; 
      } 
      else 
      { 
       return j; 
      } 
     } 


    } 
+1

我建議您一步一步調試代碼,並看看在您進行遞歸調用時'p','q'和'r'的值是如何改變的。基於這個錯誤,我猜他們沒有改變,因爲他們應該。 – carlosfigueira

+1

遞歸快速排序總是會冒吹堆棧的風險。但不是在8個元素的數組上。使用調試器來追蹤發生了什麼。 –

+0

提示:Partition()創建3個段,而不是2個。 –

回答

1

你快速排序的方法不會在情況下,它已經排序劃分後停止。

private static void QuickSort(int[] input, int p, int r) { 
    if (p < r) { 
     int q = Partition(input, p, r); 
     if (q < r) { 
      QuickSort(input, p, q); 
      QuickSort(input, q, r); 
     } 
    } 
} 
+0

這看起來仍然很容易卡住。併產生未分類的輸出。 –

+0

仍然溢出,不能再排序 –