Direct insertion sort - Simple (c language)

//

//  main.cpp

//  straightinsert_sort

//

//  Created by duanqibo on 2019/7/17.

//  Copyright © 2019年 duanqibo. All rights reserved.

// direct insertion sort

 

#include <iostream>

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define N 10

// Data type definition of the structure of the

typedef struct student

{

    int num;

    char name[20];

    char sex[2];

    int age;

} This [N];

 

// by name, direct insertion sort

void straightinsert_sort(struct student stud[], int n)

{

    int i, j;

    struct student temp;

    printf ( "\ \ t n Sort by name: \ 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;

    }

}

 

int main(int argc, const char * argv[]) {

    // insert code here...

    struct student stu1[5];

    int i, len;

    printf ( "Please enter the case five students: \ n");

    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 ( "Student ID \ t name \ t sex \ t Age \ n");

    for (i = 0; i<len; i++)

    {

        printf("%d\t%s\t%s\t%d\n", stu1[i].num,

               stu1[i].name,

               stu1[i].sex,

               stu1[i].age);

    }

    printf("%d\n", len);

    system("pause");

    return 1;

}

 

operation result:

 

Guess you like

Origin www.cnblogs.com/duanqibo/p/11200330.html
Recommended