【问题标题】:QuickSort C Median pivot elementQuickSort C 中值枢轴元素
【发布时间】: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; 部分非常有意义,而不是使用中位数时。
  • 是的,改了,但什么都没改:(

标签: c algorithm quicksort


【解决方案1】:

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

在这种情况下,函数找不到任何返回语句并且行为未定义。
尝试在条件中使用&lt;= 而不是&lt;

另外,您在使用 pivot + 1 时没有确保 pivot 不是最后一个元素。
如果中位数是数组的最后一个元素,程序会崩溃。

您确定它适用于正常输入吗,因为我尝试过并且该函数没有正确地对数组进行排序。
您可以在分区例程here 上找到很好的解释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    相关资源
    最近更新 更多