c - QuickSort C 中位数枢轴元素

标签 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;
}

我做错了什么??

提前致谢!

最佳答案

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

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

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

你确定它适用于正常输入吗,因为我试过了,但这个函数没有正确地对数组进行排序。
您可以在分区例程中找到很好的解释 here .

关于c - QuickSort C 中位数枢轴元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23932321/

相关文章:

c++ - 修复 GCC 的 #includes <> (Code::Blocks)

algorithm - 什么是对偶排序

c - 在 C 中对二维 double 组进行排序

c++ - 使用 dlopen 加载库时具有静态存储行为的动态变量

c - 保存指针的内存地址

java - 从 Java 中的 HashMap 中删除条目

c++ - 帮助理解这个算法

c++ - 快速排序的实现,几乎可以工作但不能

python - 以中间元素为轴心进行快速排序

c - 对于矩阵来说,这是正确的类型和逻辑吗?