【问题标题】:I am writing a quick sort that is supposed to keep track of the number of iterations. However, the count returns 0 every time. How can I fix this?我正在编写一个应该跟踪迭代次数的快速排序。但是,计数每次都返回 0。我怎样才能解决这个问题?
【发布时间】:2017-09-26 01:08:09
【问题描述】:

从 main 调用的函数:

int Quicksort::Sort(Data* ary, int left, int right, int count)
{
    count = SortPrivate(ary, left, right, count);
    return count;
}

进行实际排序的函数:

int Quicksort::SortPrivate(Data* ary, int left, int right, int count)
{

    if (left < right)
    {
        count++;
        int pivot = Partition(ary, left, right);

        SortPrivate(ary, left, pivot - 1, count);
        SortPrivate(ary, pivot + 1, right, count);

    }
    return count;
}

然后是这个:

int Quicksort::Partition(Data* ary, int left, int right)
{
    int pivotValue = ary[left].Get_key();
    int sortLeft = left + 1;
    int sortRight = right;
    bool finished = false;

    while (!finished)
    {
        while (sortLeft <= sortRight && ary[sortLeft].Get_key() <= pivotValue)
            sortLeft++;

        while (ary[sortRight].Get_key() >= pivotValue && sortRight >= sortLeft)
            sortRight--;

        if (sortRight < sortLeft)
            finished = true;
        else
            Exchange(ary, sortLeft, sortRight);
    }

    Exchange(ary, left, sortRight);

    return sortRight;
}

我在 Visual Studio 中使用 step into 过程进行了一些调试,结果每次递归函数返回时,它都会递减,直到计数返回 0。如何防止这种情况发生?任何提示将不胜感激。

【问题讨论】:

  • 通过以及返回 count?
  • 是的,我必须传递它,否则每次递归调用函数时它都会重置,我必须返回它才能取回值。但正如我的回答所说,为了解决这个问题,我将函数的返回类型更改为 void 并通过引用传递它。现在完美运行。
  • 那是我试图给你的指针!
  • 是的,对不起。我没有意识到它只会在每次递归结束时一直递减到零。

标签: c++ algorithm sorting data-structures


【解决方案1】:

所以我所做的是通过引用传递计数并将函数的返回类型更改为 void,现在它可以完美运行。我必须传入计数并以某种方式“返回”它,因为它是递归调用的。因此,为了实现这一点,我只是通过引用传递计数,而不是函数返回任何内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2019-04-10
    • 1970-01-01
    相关资源
    最近更新 更多