#include <stdio.h>
#include <stdlib.h>
void Swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
void BubbleSort(int arr[], int n)
{
int i, j;
for (i = n-1 ; i > 0 ; i--) // arr[n-1] ~ arr[1] put bigger number
{
for (j = 0 ; j < i ; j++) // 0,1 ~ i-1,i bubbling
{
if (arr[j] > arr[j+1])
Swap(&arr[j], &arr[j+1]);
}
}
}
/* Function to print an array */
void PrintArray(int arr[], int size)
{
printf("\n**********************\n");
for(int i=0 ; i<size ; i++)
{
printf("%4d", arr[i]);
}
}
// Driver program to test above functions
int main()
{
int array[5];
for(int i=0 ; i<5 ; i++)
{
printf("Put your %d integers : ", i);
scanf("%d", array+i);
}
PrintArray(array, sizeof(array)/sizeof(array[0]));
BubbleSort(array, sizeof(array)/sizeof(array[0]));
PrintArray(array, sizeof(array)/sizeof(array[0]));
return 0;
}
버블소트는 반복적으로 인접한 배열인자를 swap하며 작동하는 가장 간단한 정렬방법이다
- O(n^2) / Stable Sort
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
- GeeksforGeeks
'Algorithm' 카테고리의 다른 글
[C code] 버킷 정렬 (Bucket Sort) (0) | 2020.01.07 |
---|---|
[C code] 계수 정렬 (Counting Sort) (0) | 2020.01.04 |
[C code] 삽입 정렬 (Insertion sort) (0) | 2020.01.04 |
[C code] 피보나치 수열 (동적계획법 ; DP) (0) | 2020.01.04 |
[C code] 보이어-무어 알고리즘 (Boyer-Moore Algorithm) (2) | 2020.01.04 |