C++中用string字符数组,冒泡排序法编程

不用类,不用其它系统函数,不用指针。请高手们看下边这段程序错误在哪?(程序能过编译通过,但是结果并不是欲想的结果)如下:
#include<iostream>
#include<string>
using namespace std;
int main()
{

void sort(string b[]);
int i;
string a[5];
cout<<“输入5个字符串:“<<endl;
for(i=0;i<5;i++)
{
cout<<“第“<<i+1<<“个字符串:“;
cin>>a[i];
}
sort(a);
return 0;
}
void sort(string b[])
{
int i,j,p;
string temp;
for(i=0;i<5;i++)
for(j=0;j<5-i;j++)
if(b[j]<b[j+1])
{
temp=b[j];
b[j]=b[j+1];
b[j+1]=temp;
}
cout<<“输入的5个字符串从小到大排序为:“<<endl;
for(p=0;p<5;p++)
cout<<b[p]<<endl;
cout<<endl;
}

逻辑错误了。
void sort(string b[])
{
int i,j,p;
string temp;
for(i=0;i<5;i++)
for(j=0;j<5-i;j++)
if(b[j]<b[j+1])
{
temp=b[j];
b[j]=b[j+1];
b[j+1]=temp;
}
cout<<“输入的5个字符串从小到大排序为:“<<endl;
for(p=0;p<5;p++)
cout<<b[p]<<endl;
cout<<endl;
}
修改为:
void sort(string b[])
{
int i,j,p;
string temp;

for(i=0;i<5;i++)
for(j=0;j<i;j++)
if(b[j]>b[i])
{
temp=b[j];
b[j]=b[i];
b[i]=temp;
}
cout<<“输入的5个字符串从小到大排序为:“<<endl;
for(p=0;p<5;p++)
cout<<b[p]<<endl;
cout<<endl;
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2010-06-11
for(i=0;i<5-1;i++)
for(j=0;j<5-i-1;j++)
第2个回答  2010-06-11
#include<iostream>
#include<string>
using namespace std;
int main()
{

void sort(string b[]);
int i;
string a[5];
cout<<“输入5个字符串:“<<endl;
for(i=0;i<5;i++)
{
cout<<“第“<<i+1<<“个字符串:“;
cin>>a[i];
}
sort(a);
return 0;
}
void sort(string b[])
{
int i,j,p;
string temp;
for(i=0;i<4;i++)
for(j=i+1;j<5;j++)
if(b[i]>b[j])
{
temp=b[j];
b[j]=b[j];
b[j]=temp;
}
cout<<“输入的5个字符串从小到大排序为:“<<endl;
for(p=0;p<5;p++)
cout<<b[p]<<endl;
cout<<endl;
}
第3个回答  2010-06-12
for(i=0;i<5;i++)
for(j=0;j<5-i;j++)
将这两句改为:

for(i=0;i<4;i++)
for(j=0;j<4-i;j++) 即可
相似回答