#include<stdio.h> #include<iostream> using namespace std; #define MAXSIZE 20 typedef int KeyType; typedef int InfoType; typedef struct{ KeyType key; InfoType otherType; }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 pivotloc,n; if(low < high) { pivotloc = Partition(L, low, high); QSort(L, low, pivotloc-1); QSort(L, pivotloc+1, high); for(int i = 1; i <= L.length; i++) { cout<<L.r[i].key<<" "; } cout<<endl; } } void QuickSort(SqList &L) { QSort(L,1,L.length); } int main(void) { SqList L1; int i, count; for(i=0; i<MAXSIZE; i++) { L1.r[i].key = 0; } L1.length = 0; cin>>count; while(count>0 && L1.length<MAXSIZE) { cin>>L1.r[L1.length].key; L1.length++; count--; } QuickSort(L1); return 0; }修改这个代码,使得【样例输入】 5 33 65 90 78 18 【样例输出】 18 33 90 78 65 18 33 65 78 90 18 33 65 78 90
时间: 2024-01-27 10:03:24 浏览: 160
下面是修改后的代码:
```
#include <iostream>
using namespace std;
#define MAXSIZE 20
typedef int KeyType;
typedef int InfoType;
typedef struct {
KeyType key;
InfoType otherType;
} 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 pivotloc, n;
if (low < high) {
pivotloc = Partition(L, low, high);
QSort(L, low, pivotloc - 1);
QSort(L, pivotloc + 1, high);
}
}
void QuickSort(SqList& L) {
QSort(L, 1, L.length);
}
int main(void) {
SqList L1;
int i, count;
for (i = 0; i < MAXSIZE; i++) {
L1.r[i].key = 0;
}
L1.length = 0;
cin >> count;
while (count > 0 && L1.length < MAXSIZE) {
cin >> L1.r[L1.length].key;
L1.length++;
count--;
}
QuickSort(L1);
for (int i = 1; i <= L1.length; i++) {
cout << L1.r[i].key << " ";
}
cout << endl;
return 0;
}
```
修改的部分:
1. 将输出语句移动到 `QSort` 函数外部,避免多次输出。
2. 去掉了 `for` 循环中的输出语句,因为这会导致每次交换元素时都输出一遍,影响排序效率。
3. 在 `main` 函数中添加了输出语句,输出排序后的结果。
阅读全文