我通過選擇第一個元素作爲支點,實現了快速排序。它適用於一般的測試用例,但考慮一個例子,當數組被反向排序時,例如5 4 3 2 1.我知道它在哪裏拋出運行時錯誤。但我無法正確解決它。第一個元素的實現是否正確?請提出修改建議。使用第一個元素作爲支點快速排序
public static void quicksort(int low,int high)
{
if(low<high)
{
int temp=0;
int pivot=a[low];
int large_index=low+1;
int small_index=high;
while(large_index<=small_index)
{
while(a[small_index]>pivot)
small_index--;
while(a[large_index]<pivot)
large_index++;
if(large_index<=small_index)
{
temp = a[large_index];
a[large_index]= a[small_index];
a[small_index]= temp;
large_index++;
small_index--;
}
}
temp = a[small_index];
a[small_index]= a[low];
a[low]= temp;
quicksort(low,small_index-1);
quicksort(small_index+1,high);
}
}
也許嘗試使用您的調試器? – 2014-09-01 15:09:32
至少提供堆棧跟蹤。 – 2014-09-01 15:12:49
請縮進... – 2014-09-01 15:21:29