//快速排序 #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) { if (low < high) { char pivotloc; 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() { SqList L; int dt[10]; int i; cout << "输入待排序列长度和输入数据"; cin >> L.length; Quicksort(L,1,dt); return 1; }
时间: 2024-03-25 11:41:56 浏览: 137
使用include <iostream>时一定要加using namespace std
你的代码中有一些问题。首先,在 main 函数中调用 Quicksort 函数时,传入的参数个数不正确,Quicksort 函数只需要传入一个参数 SqList& L 即可,不需要传入两个参数和一个未定义的数组 dt。其次,在 Qsort 函数中,递归调用 Qsort 函数时,第二个子序列的起始下标应该是 pivotloc + 1,而不是 pivotloc +1。最后,你没有输出排序后的结果。以下是修正后的代码:
```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) {
if (low < high)
{
int pivotloc;
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() {
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;
}
```
阅读全文