Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

악어새와 좀개구리밥

[C언어] 내장함수 qsort()로 구조체 정렬 본문

알고리즘

[C언어] 내장함수 qsort()로 구조체 정렬

tiobi 2021. 10. 10. 21:30
728x90

source code

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#pragma warning(disable:4996)

#define TESTSIZE 50
#define MAXNAMESIZE 30


/*---Defining Structure---*/
typedef struct {
    unsigned int data;
    char name[MAXNAMESIZE];
}my_struct;


/*---Structure List as Global for EZ Access---*/
my_struct my_list[TESTSIZE];


/*---Function Declaration---*/
void init_list();
int my_struct_compfunc(const void*, const void*);


/*---Main Function---*/
int main() {
    init_list();


    /*Before qsort()*/
    puts("My list before quick sorting");
    for (int i = 0; i < TESTSIZE; i++) 
        printf("%d ", my_list[i].data);

    /*qsort()-ing*/
    qsort(my_list, TESTSIZE, sizeof(my_struct), my_struct_compfunc);
    printf("\n\n\n");

    /*After qsort()*/
    puts("My list after quick sorting");
    for (int i = 0; i < TESTSIZE; i++)
        printf("%d ", my_list[i].data);
    puts("");

    return 0;
}


/*---Function Definition---*/
/*Inits global list with random data*/
void init_list() {
    /* init random */
    srand(time(NULL));

    for (int i = 0; i < TESTSIZE; i++) {
        my_list[i].data = rand() % 5000;
        strcpy(my_list[i].name, "random_name_here");
    }
}

/*compfunc function for my structure*/
int my_struct_compfunc(const void* a, const void* b) {
    my_struct* structA = (my_struct*)a;
    my_struct* structB = (my_struct*)b;

    return (structB->data - structA->data);
}

내장함수인 qsort()를 사용하고 나아가 효율성이 더 좋은 quick sort 알고리즘을 만들기 위한 연습으로 구조체를 정의해서 qsort()함수를 사용해보았다. 새로운 quick sort 알고리즘을 만들어서 qsort()와 시간 비교를 할 예정이다.

qsort()의 마지막 매개변수는 크기를 비교하는 함수이다. 구조체의 data영역의 크기를 비교할 수 있도록 반환값을 설정해주면 된다.

'알고리즘' 카테고리의 다른 글

[GitHub] git push시 오류  (0) 2021.11.03
[C언어] quick sort  (0) 2021.10.12
[C언어] Fisher-Yates Shuffle  (0) 2021.10.12
[C언어]구조체로 이중연결리스트 정렬 구현  (0) 2021.09.15
Comments