[英]QuickSort C Median pivot element
我正在嘗試使用中值樞軸元素實現QuickSort算法...如果沒有數字出現兩次,我的代碼可以工作,但無論如何這都不是解決方案。 如果我選擇分區的第一個元素作為樞軸,無論值是否出現兩次或更多,代碼都是完美的...
這是我的代碼:
void quickSort(int a[ ], int from, int to)
{ // sort partition from ... to of array a
int i, pivot, new_val;
if (from < to) // at least 2 elements in partition
{
//pivot = from; --> old version, first element is pivot
pivot = median(a, from, to);
for (i = from; i <= to; i++)
{
new_val = a[i];
if (new_val < a[pivot])
{ // shift values to the right
a[i] = a[pivot+1];
a[pivot+1] = a[pivot];
a[pivot] = new_val;
pivot++;
} // else a[i] stays put
}
quickSort(a, from, pivot-1); // left partition
quickSort(a, pivot+1, to); // right partition
} // else (from >= to) only 0 or 1 elements
} // end quicksort
int median(int a[], int from, int to)
{
int med = (from + to) / 2;
if((a[from] < a[med] && a[med] <= a[to]) || (a[to] < a[med] && a[med] < a[from]))
return med;
else if((a[med] < a[from] && a[from] < a[to]) || (a[to] < a[from] && a[from] < a[med]))
return from;
else if((a[med] < a[to] && a[to] < a[from]) || (a[from] < a[to] && a[to] < a[med]))
return to;
}
我究竟做錯了什么??
提前致謝!
當某些元素彼此相等時,您的中值函數會失敗。
如果輸入為3,3和3,則函數中的條件都不會計算為true。
在這種情況下,函數找不到任何return語句,並且行為未定義。
嘗試在條件中使用<=
而不是<
。
此外,您使用pivot + 1
而不確保pivot
不是最后一個元素。
如果中位數是數組的最后一個元素,程序將崩潰。
你確定它適用於正常輸入,因為我試過並且該功能沒有正確排序數組。
您可以在此處找到有關分區例程的詳細說明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.