본문 바로가기

C

[C언어] 버블 정렬(Bubble Sort)

반응형

정렬(Sort)은 주어진 값에 따라 순서대로 나열하는 기능이다. 정렬에는 선택 정렬(Selection Sort), 삽입 정렬(Insertion Sort), 버블 정렬(Bubble Sort)이 있다.

 

#include<stdio.h>
#define SIZE 5

// 버블 정렬(Bubble Sort)
int main(){
   int score[5] = {80, 85, 90, 67, 70};
   int tmp = 0;   // 임시 변수 선언

   for(int i = 0; i < SIZE - 1; i++){      
      for(int j = i + 1; j < SIZE; j++){   // 맨 처음 숫자 한개를 뒤의 숫자들과 차례로 비교하며, 작은 수 부터 나열한다.
         if(score[i] > score[j]){          // score[i]가 score[j]보다 크면, score[i]와 score[j]의 값을 바꾸어 준다.
            tmp = score[i];
            score[i] = score[j];
            score[j] = tmp;
         }
      }
   }

   for(int i = 0; i < SIZE; i++)
      printf("%3d", score[i]);

   printf("\n");

   return 0;
}

 

반응형