c++ - C ++中的快速排序间歇性地工作
问题描述
我的快速排序算法有什么问题?有时它给出了正确的答案,有时它没有。这是我的代码。
#include <iomanip>
#include <iostream>
using namespace std;
void foo(int*, int, int);
int main()
{
int* a, n;
cin >> n;
a = new int[n];
srand(time(NULL));
for (int i = 0; i <= n - 1; i++)
{
a[i] = rand() % 100;
cout << setw(3) << a[i];
}
cout << endl;
cout << "sorting array" << endl;
foo(a, 0, n - 1);
for (int i = 0; i <= n - 1; i++)
cout << setw(3) << a[i];
cout << endl;
return 0;
}
void foo(int* a, int left, int right)
{
int j = right;
int i = left;
int mid = (i + j) / 2;
while (i < j)
{
while (a[i] < a[mid]) i++;
while (a[j] > a[mid]) j--;
if (i <= j)
{
swap(a[i], a[j]); i++; j--;
}
}
if (i < right)
foo(a, i, right);
if (left < j) foo(a, left, j);
}
我对我的程序做了一些更改,它开始正常工作,问题是我不明白为什么。我在下面的代码中提到了更改。所有预期的输出都与结果匹配。
#include <iomanip>
#include <iostream>
using namespace std;
void foo(int*, int, int);
int main()
{
int* a, n;
cin >> n;
a = new int[n];
srand(time(NULL));
for (int i = 0; i <= n - 1; i++)
{
a[i] = rand() % 100;
cout << setw(3) << a[i];
}
cout << endl;
cout << "sorting array" << endl;
foo(a, 0, n - 1);
for (int i = 0; i <= n - 1; i++)
cout << setw(3) << a[i];
cout << endl;
return 0;
}
void foo(int* a, int left, int right)
{
int j = right;
int i = left;
int mid = (a[right] + a[left]) / 2;//CHANGED LINE from mid=(i+j)/2
while (i < j)
{
while (a[i] < mid) i++; //CHANGED LINE from a[i]<a[mid]
while (a[j] > mid) j--; //CHANGED LINE from a[j]>a[mid]
if (i <= j)
{
swap(a[i], a[j]); i++; j--;
}
}
if (i < right)
foo(a, i, right);
if (left < j) foo(a, left, j);
}
解决方案
推荐阅读
- firebase - 用于检查特定字段的 Firebase 规则
- r - 根据单元格中的特定开始拆分数据集
- django - Django中的同义多对多模型关系
- php - 如何将日期名称转换为当月的日期?
- angular - “Renderer2”类型上不存在属性“projectNodes”
- android - Android KeyEvent.getCharacters() 或 keyEvent.characters 已弃用
- java - 如何从用 Java 编写的 Azure Function App 连接到 PostgreSQL?
- sql - Oracle中的正则表达式-每5个字符后放置一个字符串
- javascript - TypeError:class.function 不是函数。(在 'classname.function(param)' 中)
- php - 基本匿名用户评级系统 - 不工作