본문 바로가기

TEST/자료구조와 함께 배우는 알고리즘 입문(C언어)

<6> Q3. 자료구조와 함께 배우는 알고리즘 입문 (C언어)

#include <stdio.h>
#include <stdlib.h>
#define swap(type, x, y) \
    do                   \
    {                    \
        type t = x;      \
        x = y;           \
        y = t;           \
    } while (0)

void bubble(int a[], int n)
{
    int i, j;
    for(i=0;i<n-1;i++){
        int exchg=0;
        for(j=n-1;j>i;j--)
        if(a[j-1]>a[j]){
            swap(int ,a[j-1],a[j]);
            exchg++;
        }
        if(exchg==0)break;
    }
}

int is_sorted(const int a[],int n)
{
    for(int i = 0; i<n-1;i++){
        if(a[i]>a[i+1])
        return 0;
    }
    return 1;
}

int main(void)
{
    int i, nx;
    int *x;
    puts("버블 정렬");
    printf("요소 개수 : ");
    scanf("%d", &nx);
    x = calloc(nx, sizeof(int));

    for (i = 0; i < nx; i++)
    {
        printf("x[%d] : ", i);
        scanf("%d", &x[i]);
    }

    bubble(x, nx);
    printf("%d",is_sorted(x,nx));
    free(x);

    return 0;
}