본문 바로가기

C_study

[C] 코딩도장 73 : 배열 정렬하기

73.6 심사문제: 거품 정렬 구현하기

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int bubble_sort(int Arr[], int count)
{
    int temp;
    for(int i = 0 ; i < count; i++) // 모든 요소 개수만큼 반복합니다.
    {
        for (int j = 0; j < count - 1; j++) // 한개의 요소를 배열 끝까지 비교하면서 정렬해줍니다. 
        {
            if (Arr[j] < Arr[j + 1])
            {
                temp = Arr[j];
                Arr[j] = Arr[j + 1];
                Arr[j + 1] = temp;
            }
        }
    }
}
 

int main()
{
    int numArr[10];

    scanf("%d %d %d %d %d %d %d %d %d %d", 
        &numArr[0], &numArr[1], &numArr[2], &numArr[3], &numArr[4], 
        &numArr[5], &numArr[6], &numArr[7], &numArr[8], &numArr[9]
    );

    bubble_sort(numArr, sizeof(numArr) / sizeof(int)); // 정렬할 배열과 요소 개수를 함수에 넘겨줍니다.

    for (int i = 0; i < 10; i++)
    {
        printf("%d ", numArr[i]);
    }

    printf("\n");

    return 0;
}

73.7 심사문제: 퀵 정렬 함수 사용하기

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

int compare(const void* a, const void* b)
{
    return -strcmp((char*)a, (char*)b); // 내림차순 정렬이므로 strcmp 결과값에 -를 붙여줍니다.
}

int main()
{
    char s1[10][20];

    scanf("%s %s %s %s %s %s %s %s %s %s", 
        s1[0], s1[1], s1[2], s1[3], s1[4], s1[5], s1[6], s1[7], s1[8], s1[9]
    );

    qsort(s1, sizeof(s1) / sizeof(s1[0]), sizeof(s1[0]), compare);

    for (int i = 0; i < 10; i++)
    {
        printf("%s ", s1[i]);
    }

    printf("\n");

    return 0;
}