//程序1:编写代码排序
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
struct book
{
char n[30],a[30],p2[30];
int p;
};
int main()
{
int n,i,j;
struct book b[100];
char s[100];
while (gets(s))
{
sscanf(s,"%d",&n);
if (strlen(s)==0) break;
for (i=1; i<=n; i++)
{
gets(s);
sscanf(s,"%s%d%s%s",b[i].n,&b[i].p,b[i].a,b[i].p2);
}
for (i=1; i<=n-1; i++)
for (j=1;j<=n-i; j++)
if ( strcmp(b[j].n,b[j+1].n)>0 )
swap(b[j],b[j+1]);
for (i=1; i<=n; i++)
cout<<left<<setw(20)<<b[i].n<<setw(20)<<b[i].p
<<setw(20)<<b[i].a<<setw(20)<<b[i].p2<<endl;
cout<<endl;
}
return 0;
}
//程序2:编写排序函数,调用qsort函数排序
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
typedef struct book
{ char n[30],a[30],p2[30];
int p;
}book;
int compare(const void *x,const void *y)
{ book *a=(book*)x,*b=(book*)y;
if ( strcmp(a->n,b->n)<0 ) return -1;
else if ( strcmp(a->n,b->n)>0 ) return 1;
else return 0;
}
int main()
{
int n,i,j;
book b[100];
char s[100];
while (gets(s))
{
sscanf(s,"%d",&n);
if (strlen(s)==0) break;
for (i=0; i<n; i++)
{
gets(s);
sscanf(s,"%s%d%s%s",b[i].n,&b[i].p,b[i].a,b[i].p2);
}
qsort(b,n,sizeof(book),compare);
for (i=0; i<n; i++)
cout<<left<<setw(20)<<b[i].n<<setw(20)<<b[i].p
<<setw(20)<<b[i].a<<setw(20)<<b[i].p2<<endl;
cout<<endl;
}
return 0;
}
//程序3:编写排序函数,调用sort函数排序
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
typedef struct book
{ char n[30],a[30],p2[30];
int p;
}book;
bool compare(const book &a,const book &b)
{ if ( strcmp(a.n,b.n)<0 ) return 1;
else return 0;
}
int main()
{
int n,i,j;
book b[100];
char s[100];
while (gets(s))
{
sscanf(s,"%d",&n);
if (strlen(s)==0) break;
for (i=0; i<n; i++)
{
gets(s);
sscanf(s,"%s%d%s%s",b[i].n,&b[i].p,b[i].a,b[i].p2);
}
sort(b,b+n,compare);
for (i=0; i<n; i++)
cout<<left<<setw(20)<<b[i].n<<setw(20)<<b[i].p
<<setw(20)<<b[i].a<<setw(20)<<b[i].p2<<endl;
cout<<endl;
}
return 0;
}
//程序4:编写排序函数,调用sort函数对vector排序
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <vector>
using namespace std;
typedef struct book
{ char n[30],a[30],p2[30];
int p;
}book;
bool compare(const book &a,const book &b)
{ if ( strcmp(a.n,b.n)<0 ) return 1;
else return 0;
}
int main()
{
int n,i,j;
vector <book> v;
char s[100];
book b;
while (gets(s))
{
sscanf(s,"%d",&n);
if (strlen(s)==0) break;
for (i=0; i<n; i++)
{
gets(s);
sscanf(s,"%s%d%s%s",b.n,&b.p,b.a,b.p2);
v.push_back(b);
}
sort(v.begin(),v.end(),compare);
for (i=0; i<n; i++)
cout<<left<<setw(20)<<v[i].n<<setw(20)<<v[i].p
<<setw(20)<<v[i].a<<setw(20)<<v[i].p2<<endl;
cout<<endl;
v.clear();
}
return 0;
}
各种排序
最新推荐文章于 2022-06-11 20:07:53 发布