본문 바로가기
Algorithm

Bubble Sort(버블 정렬)

by 곰제비 2022. 6. 13.

출처) https://gmlwjd9405.github.io/2018/05/06/algorithm-bubble-sort.html

 

서로 인접한 두 원소를 검사하여 정렬하는 알고리즘

 

두 원소를 선택하여 비교하고 왼쪽이 오른쪽보다 크면 swap하며 바꾼다.

배열 내 전체 원소가 오름차순으로 정렬될 때까지 과정을 반복한다.

<시간 복잡도>

출처) https://gmlwjd9405.github.io/2018/05/06/algorithm-bubble-sort.html

<전체 코드>

# include <stdio.h>
# define MAX_SIZE 5

void bubble_sort(int list[], int n){ // 버블 정렬
  int i, j, temp;

  for(i=n-1; i>0; i--){ // 0 ~ (i-1)까지 반복
    for(j=0; j<i; j++){ // j번째와 j+1번째의 요소가 크기 순이 아니면 교환
      if(list[j]<list[j+1]){
        temp = list[j];
        list[j] = list[j+1];
        list[j+1] = temp;
      }
    }
  }
}

void main() {
  int i;
  int n = MAX_SIZE;
  int list[n] = {7, 4, 5, 1, 3};

  bubble_sort(list, n); // 버블 정렬 수행

  for(i=0; i<n; i++){ // 정렬 결과 출력
    printf("%d\n", list[i]);
  }
}

 

 

 

'Algorithm' 카테고리의 다른 글

Prefix sum(누적합)  (0) 2022.06.20
Recursion Function(재귀 함수)  (0) 2022.06.20
Time Complexity(시간 복잡도)  (0) 2022.06.20
Selection Sort(선택 정렬)  (0) 2022.06.14
GCD(최대공약수), LCM(최소공배수) C++ 구현  (0) 2022.06.14