작업 환경
- OS : Ubuntu 14.04.5 LTS
버블정렬이란?
- 인접한 두 개의 데이터를 비교해가면서 정렬하는 알고리즘
그림 참조 - 윤성우의 열혈 자료구조
문제
배열에 3,1,5,4,2를 저장하고 버블정렬을 이용하여 오름차순으로 정렬하시오.
bubble_sort.c
#include<stdio.h>
void BubbleSort(int *arr , int cnt);
int main()
{
int arr[5] = {3,1,5,4,2};
int i , cnt;
cnt = sizeof(arr) / sizeof(int);
BubbleSort(arr , cnt);
for(i=0 ; i<cnt ; ++i)
printf("%d " , arr[i]);
putchar('\n');
return 0;
}
void BubbleSort(int *arr , int cnt)
{
int i , j , temp;
for(i=0 ; i<cnt-1 ; ++i)
{
for(j=0 ; j<(cnt-i)-1 ; ++j)
{
if(arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
컴파일 : gcc bubble_sort.c -o bubble_sort
실행 : ./bubble_sort
실행결과
'Programming Skill > Data Structure & Algorithm' 카테고리의 다른 글
[알고리즘] 삽입정렬(Insertion Sort) (0) | 2017.01.30 |
---|---|
[알고리즘] 선택정렬(Selection Sort) (0) | 2017.01.30 |
[알고리즘] 간접정렬(Indirect Sort) (0) | 2017.01.29 |
[자료구조] 이중연결리스트를 이용한 전화번호 관리 프로그램 (1) | 2017.01.29 |