Ins*_*der 3 c++ sorting algorithm quicksort
我正在尝试实现快速排序算法。以下代码适用于唯一元素,但不适用于具有重复元素的数组。请告诉我我哪里做错了。此外,当我将 pivot 的值更改为 0 以外的其他数字时,程序会崩溃。这是代码:
#include <iostream>
#include <cstdlib>
using namespace std;
void swapme(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void quicksort(int *arr, int size)
{
// these two variables will take care of position of comparison
int lower = 0, upper = size - 1;
int pivot = 0; // assigns pivot
if (size <= 1)
return;
while (lower < upper)
{
while (arr[lower] < arr[pivot])
{
++lower;
}
}
while (arr[upper] > arr[pivot])
{
--upper;
}
if (upper > lower)
{
swapme(arr[upper], arr[lower]);
// upper--;
// lower++;
}
quicksort(arr, lower);
quicksort(&arr[lower + 1], size - 1 - lower);
}
int main()
{
int arr[30];
for(int j = 0; j < 30; j++)
{
arr[j] = 1 + rand() % 5000;
}
for(int j = 0; j < 30; j++)
{
cout << arr[j] << "\t";
}
cout << endl;
quicksort(arr, 30);
for(int j = 0; j < 30; j++)
{
cout << arr[j] << "\t";
}
cout << endl;
cin.get();
cin.get();
}
Run Code Online (Sandbox Code Playgroud)
更新:我终于设法让它工作了。这是固定版本:
void swapme(int &a, int &b )
{
int temp = a;
a = b;
b = temp;
}
void quicksort(int *arr, int size)
{
if (size <= 1)
return;
// These two variables will take care of position of comparison.
int lower = 0;
int upper = size-1;
int pivot = arr[upper/2]; // assigns pivot
while (lower <= upper)
{
while (arr[lower] < pivot)
++lower;
while (arr[upper] > pivot)
--upper;
if (upper >= lower)
{
swapme(arr[upper],arr[lower]);
if(arr[upper] == arr[lower])
{
// Can either increment or decrement in case of duplicate entry
upper--; // lower++;
}
}
}
quicksort(arr, lower);
quicksort( &arr[lower+1], size-1-lower);
}
Run Code Online (Sandbox Code Playgroud)
您将枢轴元素的索引存储在pivot
变量中,因此交换元素可能会在循环期间更改枢轴元素的选择。不是一个很好的主意。我建议将枢轴元素的实际值存储在里面pivot
。
另外,如果这真的不是家庭作业,为什么不简单地使用标准的图书馆设施呢?
#include <algorithm>
// ...
std::sort(arr + 0, arr + 30);
Run Code Online (Sandbox Code Playgroud)
您将获得经过高度优化和测试的代码,这些代码在任何时候都将超越您手写的 Quicksort。