본문 바로가기
SW/C C++

[C/C++] Bubble Sort

by 17Hyuk 2023. 1. 7.

버블정렬

가장 큰 값을 맨 오른쪽으로 바꾸면서 정렬

 

 

#include <stdio.h>
#include <stdlib.h>         //rand() 함수
#include <time.h>           //time() 함수
#include <windows.h>


int main()
{
    system("chcp 65001");       // gcc 한글깨짐 방지
    srand(time(NULL));			// rand()을 진짜 랜덤으로 만들기 위해 필요
    
    int random_array[20];
    int random_array_size = sizeof(random_array)/4;      // int형이므로 /4


    printf("정렬전\n");
    for(int i=0; i<random_array_size; i++)
    {
        random_array[i] = rand()%100;             // 0~99
        printf("%d ", random_array[i]);
    }


    for(int i=0; i<random_array_size; i++)
    {
        for(int j=0; j<random_array_size-i-1; j++)
        {
            if(random_array[j] > random_array[j+1])
            {
                int tmp = random_array[j];
                random_array[j] = random_array[j+1];
                random_array[j+1] = tmp;
            }
        }
    }


	printf("\n정렬후\n");
    for(int i=0; i<random_array_size; i++)
    {
        printf("%d ", random_array[i]);
    }


    return 0;

}

 

※ 따로 함수로 만든 버전

#include <stdio.h>
#include <stdlib.h>         //rand() 함수
#include <time.h>           //time() 함수
#include <windows.h>


int bubble_sort(int *array, int arr_size)
{
    for(int i=0; i<arr_size; i++)
    {
        for(int j=0; j<arr_size-i-1; j++)
        {
            if(array[j] > array[j+1])
            {
                int tmp = array[j];
                array[j] = array[j+1];
                array[j+1] = tmp;
            }
        }
    }
}


int main()
{
    system("chcp 65001");       //gcc 한글깨짐 방지
    srand(time(NULL));
    
    int random_array[20];
    int random_array_size = sizeof(random_array)/4;

    for(int i=0; i<random_array_size; i++)
    {
        random_array[i] = rand() % 100;
    }




    printf("\n정렬전\n");
    for(int i=0; i<random_array_size; i++)
    {
        printf("%d ", random_array[i]);
    }
    

    bubble_sort(&random_array[0], random_array_size);


    printf("\n정렬후\n");
    for(int i=0; i<random_array_size; i++)
    {
        printf("%d ", random_array[i]);
    }

    return 0;

}

 

'SW > C C++' 카테고리의 다른 글

[C/C++] 구조체1  (0) 2023.01.08
[C/C++] 포인터 문자열  (0) 2023.01.07
[C/C++] 재귀함수  (1) 2023.01.07
[C/C++] 포인터 연습2  (0) 2022.09.21
[C/C++] 포인터 연습1  (0) 2022.09.20

댓글