QuickSort C中位数枢轴元素

时间:2014-05-29 11:31:35

标签: c algorithm quicksort

我正在尝试使用中值枢轴元素实现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;
}

我做错了什么?

提前致谢!

1 个答案:

答案 0 :(得分:3)

当某些元素彼此相等时,您的中值函数会失败。
如果输入为3,3和3,则函数中的条件都不会计算为真。

在这种情况下,函数找不到任何return语句,并且行为未定义 在条件中尝试使用<=代替<

此外,您使用的是pivot + 1,但未确定pivot不是最后一个元素 如果中位数是数组的最后一个元素,程序将崩溃。

你确定它适用于普通输入,因为我试过并且该功能没有正确排序数组。
您可以在分区例程here上找到一个很好的解释。

相关问题