I/T/C
정렬 알고리즘 (Sort Algorithm) - 버블 정렬 (Bubble Sort)
황타
2009. 11. 16. 21:14
버블 정렬로 마치 공기방울이 수면 위로 떠오르듯 가장 큰 레코드가 한 칸씩 한 칸씩 오른쪽으로 떠올라오는 정렬입니다.
#include <stdio.h> #include <stdlib.h> typedef int boolean; const boolean FALSE = 0; const boolean TRUE = 1; // comment와 함께 배열 내용을 출력 void printArray(char* comment, int A[], int N); // 정렬 알고리즘 void bubbleSort(int A[], int N); int main(int argc, char *argv[]) { int A[] = {22, 37, 15, 19, 12}; printf("Bubble Sort\n"); printArray("Input : ", A, 5); bubbleSort(A, 5); printArray("Output : ", A, 5); printf("\n"); system("PAUSE"); return 0; } void bubbleSort(int A[], int N) { boolean sorted = FALSE; int i, j; for(i=N-1 ; (i>0)&&(!sorted) ; i--) { sorted = TRUE; for(j=0 ; j<i ; j++) { if(A[j]>A[j+1]) { int temp = A[j+1]; A[j+1] = A[j]; A[j] = temp; sorted = FALSE; } } } } void printArray(char* comment, int A[], int N) { int i; printf("%s", comment); for(i=0 ; i<N ; i++) { printf("%d\t", A[i]); } printf("\n"); }