首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

快速排序结果乱排,该如何解决

2013-07-01 
快速排序结果乱排#include iostream#include iomanipusing namespace stdtypedef double KeyType//

快速排序结果乱排

#include <iostream>
#include <iomanip>
using namespace std;
typedef double KeyType;//默认关键字类型为double
const int Maxsize=50;
struct Etype
{
char name[10];
KeyType key;//这个程序中表示货物价格
};
struct LinearList
{
Etype r[Maxsize+1];
int Length;
};
int Parttion(Etype r[],int low,int high)
{
KeyType StandardKey;
Etype Temp;
Temp=r[low];
StandardKey=r[low].key;
while(low<high)
{
while(low<high&&r[high].key>=StandardKey)
high--;
r[low]=r[high];
while(low<high&&r[high].key<=StandardKey)
low++;
r[high]=r[low];
}
r[low]=Temp;
return low;
}
void Qsort(Etype r[],int low,int high)
{
int StandardLoc;
if(low<high)
{
StandardLoc=Parttion(r,low,high);
Qsort(r,low,StandardLoc-1);
Qsort(r,StandardLoc+1,high);
}
}
void QuickSort(LinearList &L)
{
Qsort(L.r,0,L.Length-1);
}
void print(LinearList &L)
{
int i;
cout<<"*******************************"<<endl;
cout<<setw(4)<<"编号"<<setw(10)<<"名称"<<setw(10)<<"价格"<<endl;
for(i=0;i<L.Length;i++)
{
cout<<setw(4)<<i+1<<setw(10)<<L.r[i].name;
cout<<setiosflags(ios::fixed);
cout<<setw(10)<<setprecision(2)<<L.r[i].key<<endl;
}
cout<<"*******************************"<<endl;
}
int main()
{
int i;
LinearList L;
L.Length=30;
Etype a[30]={
{"卫生纸",3.02},{"牙膏",5.00},{"毛巾",8.21},
{"书",14.50},{"化妆镜",10.34},{"小刀",1.28},
{"枕套",35.00},{"钱包",49.99},{"玫瑰花束",100.00},
{"钢笔",29.73},{"矿泉水",1.20},{"台式电扇",77.55},
{"耳机",10.00},{"万能充",30.48},{"塑料杯",5.10},
{"散热器",18.50},{"可乐",3.89},{"搓衣板",18.11},
{"水桶",14.90},{"坐垫",8.88},{"塑料袋",0.20},
{"被单",67.54},{"墨镜",53.02},{"雨伞",25.00},
{"肥皂",3.81},{"沐浴露",30.28},{"洗发水",10.32},
{"面包",3.05},{"蚊香",2.70},{"凉拖鞋",9.99}
};
for(i=0;i<L.Length;i++)
L.r[i]=a[i];
cout<<"排序前购物单如下:"<<endl;
print(L);
cout<<"快速排序后购物单如下:"<<endl;
QuickSort(L);
print(L);
cin>>i;
return 0;
}

[解决办法]

int Parttion(Etype r[],int low,int high)
{
    KeyType StandardKey;
    Etype Temp;
    Temp=r[low];
    StandardKey=r[low].key;
    while(low<high)
    {
        while(low<high&&r[high].key>=StandardKey)
            high--;
        r[low]=r[high];
        //while(low<high&&r[high].key<=StandardKey)改为:
          while(low<high&&r[low].key<=StandardKey)


            low++;
        r[high]=r[low];
    }
    r[low]=Temp;
    return low;
}

热点排行