본문 바로가기
알고리즘

Bubble Sort (거품정렬)

by 2744m 2018. 10. 27.

자신과 다음원소를 비교해서 큰 것을 계속 오른쪽으로 swap한다.

맨 오른쪽을 제외하고 다시 반복한다.

<알고리즘>

bubbleSort(A[],n){
		for last <- n down to 2
			for i <- 1 to last-1
				if(A[i]>A[i+1]) then A[i] <-> A[i+1]; //원소 교환
	}
	

 

<구현>

#include <iostream>
#include <random>
#define SIZE 10
using namespace std;
int A[SIZE];
void print_arr();

void make_num() {
	for (int i = 0; i < SIZE; i++) {
		A[i] = rand() % 10;
	}
	print_arr();
}

void print_arr() {
	for (int i = 0; i < SIZE; i++) {
		cout << A[i] << ' ';
	}
	cout << endl;
}

void bubble_sort(int n) {
	if (n > 0) {
		int temp = 0;
		for (int i = 0; i < n - 1; i++) {
			if (A[i] > A[i + 1]) {
				temp = A[i + 1];
				A[i + 1] = A[i];
				A[i] = temp;
			}
		}
		bubble_sort(n - 1);
	}
}

int main() {
	ios::sync_with_stdio(0), cin.tie(0);
	make_num();
	bubble_sort(SIZE);
	print_arr();

	return 0;
}

'알고리즘' 카테고리의 다른 글

피보나치 수  (0) 2020.04.04
Union Find(합집합 찾기)  (0) 2019.08.15
[알고리즘] Select Sort (선택정렬)  (0) 2018.10.27
[알고리즘] MergeSort  (0) 2018.10.26
[MST] 크루스칼 알고리즘  (0) 2018.10.10

댓글