//
// main.cpp
// bubblec++
//
// Created by duanqibo on 2019/7/17.
// Copyright © 2019年 duanqibo. All rights reserved.
// 冒泡排序 c++
#include <iostream>
#include <string>
#include <iomanip>
#define N 4
using namespace std;
class student
{
private:
int num;
char name[20];
char sex[2];
int age;
public:
student(){};
student(int n,char na[20],char se[2],int ag)
{
num=n;
strcpy(name,na);
strcpy(sex,se);
age=ag;
}
void friend bubble_sort(student stud[],int n);
void show();
};
//按姓名冒泡排序
void bubble_sort(student stud[],int n)
{
int i,j;
student temp;
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(strcmp(stud[j].name,stud[j+1].name)>0)
{
temp=stud[j];
stud[j]=stud[j+1];
stud[j+1]=temp;
}
}
}
}
void student::show()
{
cout<<num<<setw(14)<<name<<setw(14)<<sex<<setw(14)<<age<<endl;
}
int main(int argc, const char * argv[]) {
// insert code here...
student stu[N]={student(1001,"zhang","m",20),
student(1002,"wang","f",19),
student(1003,"chen","m",19),
student(1004,"liu","f",20)};
int i,len=sizeof(stu)/sizeof(stu[0]);
cout<<"学号"<<setw(14)<<"姓名"<<setw(14)<<"性别"<<setw(14)<<"年龄"<<endl;
bubble_sort(stu,len);
for(i=0;i<len;i++)
{
stu[i].show();
cout<<endl;
}
return 1;
}
运行结果: