【C言語サンプル】
qsort関数の使い方 整数配列、ポインタ配列、構造体配列の並べ替え

4つの準備

qsortを使うには以下の4つを準備してください。
(1)ソート対象の配列
(2)配列要素数
(3)配列一つのサイズ
(4)比較関数


■整数配列をqsort

#include <stdio.h>
#include <stdlib.h>
static int         	配列名[] = { 3,1,4,1,5,9,2,6,5,3};
static const size_t 	配列要素数 = sizeof(配列名) / sizeof(配列名[0]) ;
static int 整数比較関数(const void *p1, const void *p2)
{
	int n1 = *(const int *)p1;
	int n2 = *(const int *)p2;
	return n1 - n2;
}
//整数ソート
static void DMP(char *mess,int ary[],size_t max);
int main(void){
    DMP("前:",配列名,配列要素数);
	qsort(
        配列名, 
        配列要素数, 
        sizeof(int), 
        整数比較関数
    );
	DMP("後:",配列名,配列要素数);
}
static void DMP(char *mess,int ary[],size_t max){
	printf("%s",mess);
	for (size_t i=0 ; i < max ; i++){
		printf("%d:", ary[i]);	
	}
	printf("\n");
}

n1 – n2の引き算の結果で
数値順にソートします。


■ポインタ配列をqsort

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char *配列名[]={
    "moshi","moshi","kame","yo", 
    "kamesan","yo","sekai","no","uchini"
};
static const size_t 配列要素数 = sizeof(配列名) / sizeof(配列名[0]) ;
static int 文字列比較関数(const void *argv1,const void *argv2){
    const char *s1 = ((char *const*)argv1)[0];
	const char *s2 = ((char *const*)argv2)[0];
    return 	strcmp(s1,s2) ;
}
//文字列ソート
static void DMP(char *mess,char *ary[],size_t max);
int main(void){
    DMP("前:",配列名,配列要素数);
	qsort(
        配列名, 
        配列要素数, 
        sizeof(char *), 
        文字列比較関数
    );
    DMP("後:",配列名,配列要素数);
}
static void DMP(char *mess,char *ary[],size_t max){
	printf("%s\t",mess);
	for (size_t i=0 ; i < max; i++){
		printf("%s:", ary[i]);	
	}
    printf("\n");
}

strcmp()で辞書並びにソートします。


■構造体配列をqsort

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
	char 	名前[128];
	int		年齢;
	char 	郵便番号[128];
} tag_t ;
static tag_t 配列名[]={
	{.名前="佐藤",.年齢=98,	.郵便番号="111-2345"},
	{.名前="鈴木",.年齢=108,.郵便番号="222-3456"},
	{.名前="田中",.年齢=88,	.郵便番号="333-4567"},
	{.名前="加藤",.年齢=78,	.郵便番号="111-2345"},
    {.名前="伊藤",.年齢=78,	.郵便番号="333-4567"},
    {.名前="武藤",.年齢=78,	.郵便番号="222-3456"},
    {.名前="須藤",.年齢=78,	.郵便番号="111-2345"},
};
static const size_t 配列要素数 = sizeof(配列名) / sizeof(配列名[0]) ;
static int 構造体比較関数(const void *p1, const void *p2){
    //第1ソートキーを年齢とする
    int n1 = ((const tag_t *)p1)->年齢;
    int n2 = ((const tag_t *)p2)->年齢;
    if(n1 != n2){
	    return n1 - n2;
    }
    //第2ソートキーを郵便番号とする
    const char *s1 = ((const tag_t *)p1)->郵便番号;
    const char *s2 = ((const tag_t *)p2)->郵便番号;
    return  strcmp(s1,s2);
}
// 	構造体ソート
static void DMP(char *mess,tag_t ary[],size_t max);
int main(void){
    DMP("前:",配列名,配列要素数);
	qsort(
        配列名, 
        配列要素数, 
        sizeof(tag_t), 
        構造体比較関数
    );
    DMP("後:",配列名,配列要素数);
}
static void DMP(char *mess,tag_t ary[],size_t max){
    printf("%s\n",mess);
    for(size_t i = 0;i < max;i++) {
    	printf("年齢=%-3d 〒=%s 名前=%s\n",
            ary[i].年齢,
            ary[i].郵便番号,
            ary[i].名前
        );
	}
}

第1ソートキーを年齢(若い順)
第2ソートキーを郵便番号(辞書並び)
としています。