Monday, 28 September 2015

Bubble Sort

Today we will be discussing about bubble sort . In this sorting the biggest bubble(ie maximum number) will go on the end position after first iteration . 
Then we will move the second largest bubble(ie second largest number) on the second last  position.
and so on . 
So the simple program for bubble sort is 

 #include<stdio.h>
void main()
{
    int A[]={23,76,4,12,76,32,98,54,13,65};
    int size = sizeof A/sizeof A[0];
    bubble_sort(A,size);
    output(A,size);
}

void bubble_sort(int *A,int size)
{
    int i,j;
    for(i=0;i<size-1;i++)
    {
        for(j=0;j<size-i-1;j++)
        {
            if(A[j]>A[j+1])
            {
                swap(&A[j],&A[j+1]); /* swap the number if first number is larger as we are trying to                                                                             move the larger number in end */
            }
        }
    }
}
void swap(int *m, int *n)
{
    int temp = *m;
    *m=*n;
    *n=temp;
}

void output(int *A,int size)
{
    int i=0;
    for(i=0;i<size;i++)
    {
        printf("%d\n",A[i]);

    }
}

No comments:

Post a Comment