【问题标题】:Sorting the array gives erroneous values对数组进行排序会给出错误的值
【发布时间】:2021-08-02 02:42:39
【问题描述】:

我已经在 C++ 中实现了快速排序。以下是我的代码。

#include <iostream>
using namespace std;

template <typename T>
void swap(T *a, T *b)
{
    T temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

template <typename T>
void PrintArray(T arr[], int n)
{
    cout << "---------- Array ----------" << endl;
    for (int i=0; i<n ; i++)
    {
        cout << arr[i] <<'\t';
    }
    cout << endl;
}

template <typename T>
int partition(T arr[], int low, int high)
{   
    T pivot = arr[low];
    int i = low+1, j = high;
    do
    {
        while (pivot >= arr[i])
        {
            i += 1;
        }

        while (pivot < arr[j])
        {
            j -= 1;
        }

        if (i<j)
        {
            swap<T>(arr[i], arr[j]);
        }

    }while( i < j);

    swap<T>(arr[low], arr[j]);
    return j;  
}

template <typename T>
void quick_sort(T arr[], int low, int high)
{
    if (low < high)
    {
        int parition_index;
        parition_index = partition<T>(arr, low, high);

        quick_sort<T>(arr, low, parition_index-1);

        quick_sort<T>(arr, parition_index+1, high);
    }       
}

int main()
{
    // Array creation
    int n = 8;
    int a[] ={4, 3,2, 1, 18, -1, 89, -200};
    
    // Array sorting
    quick_sort<int>(a,0, n);
    PrintArray<int>(a, n);

    return 0;
}

它在大多数情况下给出排序数组,即-200, -1, 1, 2, 3, 4, 18, 89。但是,重新运行代码可能会在某些索引处产生垃圾值(例如:-968225408, -200, -1, 1, 2, 3, 4, 18)。为了检查,我用 https://www.geeksforgeeks.org/quick-sort/ 帖子中的块中的函数替换了上面代码中的所有函数。尽管如此,问题仍然存在。

代码可能有什么问题,问题的解决方案是什么。

【问题讨论】:

  • 您应该知道您的swap 函数没有被使用。如果编译成功,那是因为&lt;iostream&gt; 正在拉入std::swap,而您的using namespace std; 允许不合格的swap 调用使用std::swap。您的 swap 函数需要指针。
  • 使用std::swap。无需重新发明轮子。
  • 单步调试调试器清楚地表明j8 第一次调用partition。这会导致您与 arr[8] 进行交换,这超出了界限和未定义的行为。
  • 您从 gfg 复制的代码是垃圾。我不喜欢说别人的工作坏话,但是看到那里的废话很常见,许多初学者复制他们的代码并对这些问题感到惊讶。它只是没有帮助。
  • 数组的所有更改都通过一行进行,特别是swap&lt;T&gt;(arr[i], arr[j]);。这使得添加诊断变得容易,以帮助您发现问题所在。 (调试器对于每次执行时可重现的事情很有用;对于仅在某些时候发生的事情,某种日志记录会更方便。)试试std::cerr &lt;&lt; "Swapping indices " &lt;&lt; i &lt;&lt; " and " &lt;&lt; j &lt;&lt; "; values " &lt;&lt; arr[i] &lt;&lt; " and " &lt;&lt; arr[j] &lt;&lt; ".\n"; swap&lt;T&gt;(arr[i], arr[j]);

标签: c++ algorithm sorting quicksort


【解决方案1】:

@FrançoisAndrieux cmets 在找出问题方面非常有用。

正如他指出的那样,j 将 8 作为超出范围的值。 解决问题

第 1 步:quick_sort&lt;int&gt;(a,0, n-1); 中的 int main()

步骤 2:关闭自定义 swap 函数

【讨论】:

  • Here's 代码的简化版本。我使用最右边的元素作为枢轴。
猜你喜欢
  • 1970-01-01
  • 2014-12-11
  • 1970-01-01
  • 2019-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多