[알고리즘] 자료형 버블정렬 (Custom Type Bubble Sort)

특정 타입의 값에 대해 버블정렬하는 C 예시입니다.
정렬하는 부분과 교환하는 부분을 독립된 함수로 구성하고 정렬을 재귀(Recursive)로 구현하였습니다.

// 다른 라이브러리는 이미 include 되었다고 가정합니다

typedef struct
{
    string name;
    int scores;
} candidate;

candidate candidates[9];

int bubble_sort()
{
    int sort_counter = 0;
    for (int i = 0; i < 8; i++)
    {
        // 두개를 비교해 해당 값이 크다면 교환합니다.
        if (candidates[i + 1].name != NULL && (candidates[i].scores > candidates[i + 1].scores))
        {
            swap(&candidates[i], &candidates[i + 1]);
            sort_counter++;
        }
    }
    // 정렬이 끝나지 않으면 반복합니다
    if (sort_counter > 0)
    {
        sort_counter = bubble_sort();
    }
    return sort_counter;
}

void swap(candidate *a, candidate *b)
{
    candidate tmp = *a;
    *a = *b;
    *b

이렇게 정렬되면 가장 큰값을 가진 타입이 Array의 마지막 Element입니다.

candidate result = candidates[9];

댓글 남기기