数据结构,快速排序法,程序是老师给的,执行的时候出问题(排序结果里有很多858993460)改程序!

#include <iostream.h>
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define EQ(a,b) ((a) == (b))
#define LT(a,b) ((a) < (b))
#define LQ(a,b) ((a) <= (b))
#define MAXSIZE 20 // 一个用作示例的小顺序表的最大长度
typedef int KeyType; //定义关键字类型为整型

typedef struct { //记录类型
int key; //关键字项
int otherinfo; //其它数据项,具体类型在主程中定义
} RedType;

typedef struct { //顺序表类型
int r[MAXSIZE+1]; //r[0]闲置或用作哨兵单元
int length; //顺序表长度
} Sqlist;

//一分为二
int Partition(Sqlist &L,int low,int high)
{ // 交换顺序表L中子表L.r[low..high]的记录,使枢轴记录到位,
// 并返回其所在位置,此时在它之前(后)的记录均不大(小)于它
int pivotkey,t;
pivotkey=L.r[low]; //用子表的第一个记录作枢轴记录
while(low<high) { // 从表的两端交替地向中间扫描
while(low<high && L.r[high]>=pivotkey) --high;
t=L.r[low] ;L.r[low]=L.r[high]; L.r[high]=t; //将比枢轴记录小的记录交换到低端
while(low<high && L.r[low]<=pivotkey) ++low;
t=L.r[low] ;L.r[low]=L.r[high]; L.r[high]=t; //将比枢轴记录大的记录交换到高端
}
L.r[low]=L.r[0]; return low; //返回枢轴所在位置
}

//快速排序
void QSort(Sqlist &L,int low,int high)
{ //对顺序表L中的子序列L.r[low..high]作快速排序。
int pivotloc;
if(low<high) { //长度大于1
pivotloc=Partition(L, low, high); //将L.r[low..high]一分为二
QSort(L, low, pivotloc-1); //对低子表递归排序,pivotloc是枢轴位置
QSort(L, pivotloc+1, high); // 对高子表递归排序
}
}

//主程序
void main()
{
Sqlist L;
int i,low,high;
cout<<"输入顺序表的长度";
cin>>L.length;
for(i=1;i<=L.length;i++)
cin>>L.r[i];
low=1;
high=L.length;
QSort(L,low,high);
for(i=1;i<=L.length;i++)
{printf("%d",L.r[i]);printf(" ");}
printf("\n");

}

第1个回答  2010-11-24
我给你修改好了。
这个是正确的代码 http://paste.ideaslabs.com/show/tNi37jetd

我修改了很长时间,也不在的几处错了,
int Partition(Sqlist &L,int low,int high)
函数里面多了我注释的这一句。这个是一定错了。
//L.r[low]=L.r[0];
return low; //返回枢轴所在位置

参考资料:ogin_u

第2个回答  2010-11-24
int Partition(Sqlist &L,int low,int high)函数中,最后一行
L.r[low]=L.r[0]; return low; //返回枢轴所在位置
改为:L.r[0]=L.r[low]; return low;本回答被提问者采纳
相似回答