在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
// // main.cpp // straightinsert_sortc++ // // Created by duanqibo on 2019/7/17. // Copyright © 2019年 duanqibo. All rights reserved. // 直接插入排序 c++
#include <iostream> #include <string> #define N 5 using namespace std; //定义学生类 class student { private: int num; char name[20]; char sex[20]; 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 straightinsert_sort(student stud[],int n); //友元函数 void show();
}; //按姓名直接插入排序 void straightinsert_sort(student stud[],int n) { int i,j; student temp; printf("\n\t按学生姓名排序\n\n"); for(i=1;i<n;i++) { temp=stud[i]; j=i-1; while((j>=0)&&(strcmp(temp.name,stud[j].name)<0)) { stud[j+1]=stud[j]; j--; } stud[j+1]=temp; } }
void student::show() { cout<<num<<'\t'<<name<<'\t'<<sex<<'\t'<<age<<'\t'<<endl; }
int main(int argc, const char * argv[]) { // insert code here... student stu[N]={student(1001,"zhangsan","m",20), student(1002,"lisi","f",19), student(1003,"wangwu","m",18), student(1004,"zhaoliu","m",19), student(1005,"maqiang","m",20) }; int len=sizeof(stu)/sizeof(stu[0]); straightinsert_sort(stu,len); cout<<"学号"<<'\t'<<"姓名"<<'\t'<<"性别"<<'\t'<<"年龄"<<endl; for(int i=0;i<len;i++) { stu[i].show(); cout<<endl; } return 0; }
运行结果:
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论