//
// main.cpp
// straightinsert_sort
//
// Created by duanqibo on 2019/7/17.
// Copyright © 2019年 duanqibo. All rights reserved.
// 直接插入排序
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10
//定义结构体的数据类型
typedef struct student
{
int num;
char name[20];
char sex[2];
int age;
}stu[N];
//按姓名,直接插入排序
void straightinsert_sort(struct student stud[], int n)
{
int i, j;
struct student temp;
printf(" 按姓名排序: ");
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;
}
}
int main(int argc, const char * argv[]) {
// insert code here...
struct student stu1[5];
int i, len;
printf("请输入5个学生的情况: ");
for (i = 0; i<5; i++)
{
scanf("%d%s%s%d", &stu1[i].num,
stu1[i].name,
stu1[i].sex,
&stu1[i].age);
}
len = sizeof(stu1) / sizeof(stu1[0]);
straightinsert_sort(stu1, len);
printf("学号 姓名 性别 年龄 ");
for (i = 0; i<len; i++)
{
printf("%d %s %s %d ", stu1[i].num,
stu1[i].name,
stu1[i].sex,
stu1[i].age);
}
printf("%d ", len);
system("pause");
return 1;
}
运行结果: