【发布时间】:2014-05-29 11:31:35
【问题描述】:
我正在尝试使用中值枢轴元素实现快速排序算法... 我的代码有效,如果没有数字出现两次,但这无论如何都不是解决方案。 代码完美运行,如果我选择分区的第一个元素作为枢轴,无论值是否出现两次或更多......
这是我的代码:
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;
}
我做错了什么??
提前致谢!
【问题讨论】:
-
当 pivot == from 时,
for (i = from + 1;部分非常有意义,而不是使用中位数时。 -
是的,改了,但什么都没改:(