数据结构快速排序的问题,为什么排序后输出不出来

#include <iostream>
using namespace std;
typedef int Keytype;
Keytype NUM[10]={2,98,123,54,67,88,4,900,56,76};
struct LinearList
{
Keytype *key;
int length;
int maxsize;
};
void CreatLinearList(LinearList &L,int Maxsize)
{
L.maxsize=Maxsize;
L.length=0;
L.key=new Keytype[L.maxsize];
};
int Partition(Keytype r[],int low,int high)
{
Keytype temp;
int StandardKey;
StandardKey=r[low];
temp=r[low];
if(low<high)
{
while(low<high&&StandardKey<=r[high])
high--;
r[low++]=r[high];
while(low<high&&StandardKey>=r[high])
low++;
r[high--]=r[low];
}
r[high]=temp;
return high;
}
void QSort(Keytype r[],int low,int high)
{
int StandardLoc;
while(low<high-1)
{
StandardLoc=Partition(r,low,high);
QSort(r,low,StandardLoc-1);
QSort(r,StandardLoc+1,high);
}
}
void QuickSort(LinearList &L)
{
QSort(L.key,0,L.length-1);
}
void Output(LinearList &L)
{
for(int i=0;L.length!=0;L.length--,i++)
{
cout<<L.key[i]<<" ";
}
}
int main()
{
LinearList L;
CreatLinearList(L,20);
int i;
for(i=0;i<10;i++)
{
L.key[i]=NUM[i];
L.length++;
}
Output(L);
QuickSort(L);
cout<<endl;
Output(L);
}

有几个地方写错了,参考下面代码,在你的代码的基础上修改的,有说明:

#include <iostream>

using namespace std;

typedef int Keytype;

Keytype NUM[10]={2,98,123,54,67,88,4,900,56,76};

struct LinearList{ 

 Keytype *key;

 int length; int maxsize;

};

void CreatLinearList(LinearList &L,int Maxsize){

 L.maxsize=Maxsize;

 L.length=0;

 L.key=new Keytype[L.maxsize];

};//多了个;号,但不会出错

int Partition(Keytype r[],int low,int high){

 Keytype temp; 

 int StandardKey;

 StandardKey=r[low];

 temp=r[low];//temp变量多余,直接用StandardKey即可

 while(low<high){ //必须是(把if改成while)循环,即需多次交换

  while(low<high&&StandardKey<=r[high]) 

   high--; 

  r[low]=r[high]; //考虑可能是单支(即无法一分为二,你的题目就如此,第一个数2最小),不能是low++

  while(low<high&&StandardKey>=r[low]) 

   low++; 

  r[high]=r[low];//不能是high--

 }

 r[low]=temp;

 return low;

}

void QSort(Keytype r[],int low,int high){

 if(low<high){//这是递归调用,不需循环,条件改为low<high

  int StandardLoc;

  int L=low,H=high;//由于形参在函数中改变,故必须先保存

  StandardLoc=Partition(r,low,high); 

  QSort(r,L,StandardLoc-1);   //修改 

  QSort(r,StandardLoc+1,H); //修改

 }

}

void QuickSort(LinearList &L){

 QSort(L.key,0,L.length-1);

}

void Output(LinearList &L){ 

 for(int i=0;i<L.length;i++)

 {

  cout<<L.key[i]<<" "; 

 }

}

int main() {

 LinearList L; CreatLinearList(L,20); int i;

 for(i=0;i<10;i++)

 { 

  L.key[i]=NUM[i];

  L.length++; 

 }

 Output(L); 

 QuickSort(L);

 cout<<endl;

 Output(L);

}

温馨提示:答案为网友推荐,仅供参考
相似回答