구조체 배열, 데이터 담아서 sorting 하기(버블정렬)
#include <stdio.h>
#include <string.h>

typedef struct _employee
{
    char name[10];
    int  age;
    char company[20];
}employee;

employee em_arr[3];

int main (void)
{
    int i;

    for ( i=0; i<3; i++)
    {
    printf("Input [%d]st employee's information\n", i+1);
    printf("name:");
    scanf("%s", em_arr[i].name);
    printf("age:");
    scanf("%d", &em_arr[i].age);
    printf("company:");
    scanf("%s", em_arr[i].company);
    }

    //sorting
    int j;
    char temp_name[10];
    int  temp_age;
    char temp_company[20];

    for ( i=0; i<3; i++)
    {
        for ( j=0; j<3-(i+1); j++)
        {
            if (strcmp(em_arr[j].name, em_arr[j+1].name) > 0 )
            {
                strcpy (temp_name, em_arr[j].name);
                temp_age =  em_arr[j].age;
                strcpy (temp_company, em_arr[j].company);

                strcpy (em_arr[j].name, em_arr[j+1].name);
                em_arr[j].age = em_arr[j+1].age;
                strcpy (em_arr[j].company, em_arr[j+1].company);
                
                strcpy (em_arr[j+1].name, temp_name);
                em_arr[j+1].age = temp_age;
                strcpy (em_arr[j+1].company, temp_company);
             }
        }
    }

    for ( i=0; i<3; i++)
    {
        printf("\n====%dst employee's information ====\n", i+1);
        printf("name:%s\n", em_arr[i].name);
        printf("age: %d\n", em_arr[i].age);
        printf("company: %s\n", em_arr[i].company);
    }
    return 0;
}

+ Recent posts