把上面代码的main函数改成输出每一次排序的结果
时间: 2024-03-25 18:42:03 浏览: 15
在 Quicksort 函数中加入一个参数 int depth,用来记录当前递归的深度。在每次递归结束之后输出排序的结果。以下是修改后的代码:
```c++
//快速排序
#include<iostream>
using namespace std;
#define MAXSIZE 20
typedef int KeyType;
typedef struct {
KeyType key;
//InfoType otherinfo;
}Redtype;
typedef struct {
Redtype r[MAXSIZE + 1];
int length;
}SqList;
int Partition(SqList& L, int low, int high) {
int pivotkey;
L.r[0] = L.r[low];
pivotkey = L.r[low].key;
while (low < high)
{
while (low < high && L.r[high].key >= pivotkey) --high;
L.r[low] = L.r[high];
while (low < high && L.r[low].key <= pivotkey) ++low;
L.r[high] = L.r[low];
}
L.r[low] = L.r[0];
return low;
}
void Qsort(SqList& L, int low, int high, int depth) {
if (low < high)
{
int pivotloc;
pivotloc = Partition(L, low, high);
Qsort(L, low, pivotloc - 1, depth + 1);
cout << "第" << depth << "次排序结果:";
for (int i = 1; i <= L.length; i++) {
cout << L.r[i].key << " ";
}
cout << endl;
Qsort(L, pivotloc + 1, high, depth + 1);
cout << "第" << depth << "次排序结果:";
for (int i = 1; i <= L.length; i++) {
cout << L.r[i].key << " ";
}
cout << endl;
}
}
void Quicksort(SqList& L) {
Qsort(L, 1, L.length, 1);
}
int main() {
SqList L;
int i;
cout << "输入待排序列长度和输入数据: ";
cin >> L.length;
for (i = 1; i <= L.length; i++) {
cin >> L.r[i].key;
}
Quicksort(L);
cout << "排序后的结果:";
for (i = 1; i <= L.length; i++) {
cout << L.r[i].key << " ";
}
cout << endl;
return 0;
}
```