/*
    qsort関数を用いて配列をソート
*/

#include  <stdio.h>
#include  <stdlib.h>
#include  <string.h>

typedef struct {
    char  name[10];     /* 名前 */
    int   height;       /* 身長 */
    int   weight;       /* 体重 */
} person;

/*--- person型オブジェクトの比較関数（名前昇順） ---*/
int npcmp(const person *x, const person *y)
{
    return (strcmp(x->name, y->name));
}

/*--- person型オブジェクトの比較関数（身長昇順） ---*/
int hpcmp(const person *x, const person *y)
{
    return (x->height < y->height ? -1 :
            x->height > y->height ?  1 : 0);
}

/*--- person型オブジェクトの比較関数（体重降順） ---*/
int wdcmp(const person *x, const person *y)
{
    return (x->weight < y->weight ?  1 :
            x->weight > y->weight ? -1 : 0);/* 降順 */
}

/*--- 一人分のデータを表示 ---*/
void print_person(person x)
{
    printf("%-10.10s %dcm %dkg\n", x.name, x.height, x.weight);
}

int main(void)
{
    int  i;
    person x[]= {{"Shibata", 170, 52},
                 {"Takaoka", 180, 70},
                 {"Nangoh",  172, 63},
                 {"Yamada",  165, 83},
                };
    int  nx = sizeof(x) / sizeof(x[0]);     /* 配列xの要素数 */

    puts("ソート前");
    for (i = 0; i < nx; i++)
        print_person(x[i]);

    /* 名前昇順にソート */
    qsort(x, nx, sizeof(person), (int(*)(const void*, const void*))npcmp);

    puts("\n名前昇順ソート後");
    for (i = 0; i < nx; i++)
        print_person(x[i]);

    /* 身長昇順にソート */
    qsort(x, nx, sizeof(person), (int(*)(const void*, const void*))hpcmp);

    puts("\n身長昇順ソート後");
    for (i = 0; i < nx; i++)
        print_person(x[i]);

    /* 体重降順にソート */
    qsort(x, nx, sizeof(person), (int(*)(const void*, const void*))wdcmp);

    puts("\n体重降順ソート後");
    for (i = 0; i < nx; i++)
        print_person(x[i]);

    return (0);
}
