核心:比较排序,交换排序。两个哨兵。
#include<iostream>
#include<ctime>
using namespace std;
int* a;
void swapp(int i, int j) {
int c = a[i];
a[i] = a[j];
a[j] = c;
}
void qsort(int i,int j) {
if (i >= j){ //基础条件是要进行排序的序列只有一个关键字了
return;
}
int temp = a[i]; //该序列开头的位置
int tempi = i;//后续交换以及划分需要
int tempj = j;
while (true) {
while (j > i && a[j] >= temp) {
j--;
}
while (i <= j && a[i] <= temp)
{
i++;
}
if (i < j) {
swapp(i, j);
}
else {
if (i != j) {
swapp(tempi, j);
}
qsort(tempi, j - 1);
qsort(j + 1, tempj);
break;
}
}
}
void print(int n) {
cout << "排序后的序列为:" << endl;
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
}
int main() {
int m,n,c;
cout << "此程序实现快速排序,将n长度的序列排序后以升序顺序输出,请输入测试次数:";
cin >> m;
for (int i = 0; i < m; i++) {
cout << "请输入n:";
cin >> n;
cout << "程序随机产生序列输入1,自行输入输入2:";
cin >> c;
if (c == 1) {
srand(time(0));
a = new int[n];
cout << "随机产生的序列为:";
for (int j = 0; j < n; j++) {
a[j] = rand() % 100;
cout << a[j] << " ";
}
cout << endl;
qsort(0, n - 1);
print(n);
}
else if (c == 2) {
a = new int[n];
cout << "请依次输入要进行排序的数字:";
for (int j = 0; j < n; j++) {
cin >> a[j]; //有警告的地方一定有问题
}
qsort(0, n - 1);
print(n);
}
}
return 0;
}