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