0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C言語 qsort(クイックソート)の使い方

Posted at

C言語には配列をソートするための便利な関数 qsort が標準ライブラリ に用意されています。 今回はこの qsort の使い方を解説します。 qsort はクイックソート(Quick Sort)アルゴリズムをベースにした汎用的なソート関数です。
void qsort(void *base, size_t nitems, size_t size,
           int (*compar)(const void *, const void *));


使用例1 数字を昇順でソート
#include <stdio.h>
#include <stdlib.h>

int compare_int(const void *a, const void *b) {
    // aとbをint型にキャストして比較
    return (*(int*)a - *(int*)b);
}

int main() {
    int data[] = {5, 2, 9, 1, 3};
    int size = sizeof(data) / sizeof(data[0]);

    qsort(data, size, sizeof(int), compare_int);

    for (int i = 0; i < size; i++) {
        printf("%d ", data[i]);
    }
    printf("\n");

    return 0;
}

出力

1 2 3 5 9

使用例2 構造体を構造体の特定の要素(人の年齢)で昇順ソート

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

typedef struct {
    char name[20];
    int age;
} Person;

int compare_by_age(const void *a, const void *b) {
    const Person *pa = (const Person*)a;
    const Person *pb = (const Person*)b;

    return pa->age - pb->age;
}

int main() {
    Person people[] = {
        {"Taro", 25},
        {"Hanako", 22},
        {"Jiro", 30}
    };
    int size = sizeof(people) / sizeof(people[0]);

    qsort(people, size, sizeof(Person), compare_by_age);

    for (int i = 0; i < size; i++) {
        printf("%s (%d)\n", people[i].name, people[i].age);
    }

    return 0;
}

出力

Hanako (22)
Taro (25)
Jiro (30)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?