본문 바로가기
프로그래밍/C언어

[정렬] 버블 정렬

by 조원일 2020. 11. 4.
728x90

 

  1. 자료구조
    1. 연결 리스트
    2. 이진 트리
    3. 스택
    4. 해시
  2. 정렬
    1. 버블 정렬
    2. 선택 정렬
    3. 삽입 정렬
    4. 퀵 정렬
    5. 힙 정렬
  3. 알고리즘
    1. 재귀 함수
    2. 너비 우선탐색(BFS)
    3. 깊이 우선탐색(DFS)
    4. 다익스트라

 

버블정렬(Bubble Sort)

Bubble Sort

버블 정렬은 인접한 두 변수를 비교하여 정렬하는 방법이다.

 

시간 복잡도 : O(n^2)

 


 

소스코드

#define __main

#ifdef __main

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX_SIZE 10

void Init(int arr[]) {
	srand(time(NULL));
	for (int i = 0; i < MAX_SIZE; i++) {
		// 임의의 정수 입력
		arr[i] = rand() % 10000;
	}
}

void swap(int* a, int* b) {
	int tmp;

	tmp = *a;
	*a = *b;
	*b = tmp;
}

void Bubble_Sort(int arr[]) {
	for (int i = MAX_SIZE - 1; i > 0; i--) {
		for (int j = 0; j < i; j++) {
			if (arr[j] > arr[j + 1]) swap(&arr[j], &arr[j + 1]);
		}
	}
}

void Print(int arr[]) {
	for (int i = 0; i < MAX_SIZE; i++) {
		printf("[%d] -> %d\n", i, arr[i]);
	}
	printf("\n--------------------\n\n");
}

int main() {
	int arr[MAX_SIZE];

	Init(arr);

	Print(arr);

	Bubble_Sort(arr);

	Print(arr);

	return 0;
}

#endif

'프로그래밍 > C언어' 카테고리의 다른 글

[정렬] 삽입 정렬  (0) 2020.11.09
[정렬] 선택 정렬  (0) 2020.11.06
[자료구조] 해시  (0) 2020.11.01
[자료구조] 큐  (0) 2020.11.01
[자료구조] 스택  (0) 2020.10.30