본문 바로가기

Algorithm

[C code] 버블 정렬 (Bubble sort)

반응형
#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

반응형