C_C++

(C언어) 버블 정렬 Bubble Sort

enjoy-country-life 2022. 10. 2. 15:00
반응형

버블 정렬(bubble sort)

버블 정렬(bubble sort)은 서로 이웃하는 데이터들을 비교해서 서로 교환하는 방식으로 정렬합니다.

#include <stdio.h>

void print(int a[], int size) {
	int i;
	for (i = 0; i < size; i++)
		printf("%d ", a[i]);
	printf("\n");
}

void bubble_sort(int a[], int size) {
	int i, j, t;
	int temp;
	for (i = size - 1; i > 0; i--) {
		for (j = 0; j < i; j++) {
			if (a[j] > a[j + 1]) {   // 오름 차순 정렬
				temp = a[j];
				a[j] = a[j + 1];
				a[j + 1] = temp;
			}
		}
	}
}

int main() {
	int list[8] = { 69, 10, 30, 2, 16, 8, 31, 22 };
	int size = 8;
	print(list, size);
	bubble_sort(list, size);
	print(list, size);
}

 

 

 

다음 코드는 버블 정렬의 각 단계별로 교환과정을 출력하는 예제입니다.
버블 정렬은 n-1 단계까지 진행하게 됩니다.

#include <stdio.h>

void print(int a[], int size) {
	int i;
	for (i = 0; i < size; i++)
		printf("%d ", a[i]);
	printf("\n");
}

void bubble_sort(int a[], int size) {
	int i, j, temp;
	for (i = size - 1; i > 0; i--) {
		printf("\n[%d단계]\n", size - i);
		for (j = 0; j < i; j++) {
			if (a[j] > a[j + 1]) {
				temp = a[j];
				a[j] = a[j + 1];
				a[j + 1] = temp;
			}
			print(a, size);
		}
	}
}

int main() {
	int list[8] = { 69, 10, 30, 2, 16, 8, 31, 22 };
	int size = 8;
	print(list, size);
	bubble_sort(list, size);
	print(list, size);
}

버블정렬, 각 단계별 정렬 과정

 

 

버블 정렬은 아래와 같이도 표현할 수 있습니다.

    for (i=0;i<N-1;i++) 
    {
         for (j=N-1;j>i;j--) 
         {
              if (a[j]<a[j-1]) 
              {
                  t = a[j]; 
                  a[j] = a[j-1]; 
                  a[j-1] = t;
            }
        }
    }

 

728x90
반응형