Navigation Menu

Currently the navigation bar is not functioning. Use the Blog Archive or the Google Custom Search to find content.

Sunday 9 June 2013

C program to implement Bubble sort

C program to implement Bubble sort.
What is Bubble sort? Click here to read about it.
Bubble sort can be used to sort the items in ascending or descending order. It involves iterating through the list and swapping the adjacent elements until the list is sorted that is no swaps are needed.

Example :
45 36 28 10 5

Pass 0 :  45  36  28  10  5
Pass 1 :  36  28  10  5   45
Pass 2 :  28  10  5   36  45
Pass 3 :  10  5   28  36  45
Pass 4 :  5   10  28  36  45
Links that you may find important :

http://www.sorting-algorithms.com/bubble-sort
http://www.algolist.net/Algorithms/Sorting/Bubble_sort
http://www.algorithmist.com/index.php/Bubble_sort
http://www.youtube.com/watch?v=tT4bJB0J4H4
http://www.youtube.com/watch?v=NiyEqLZmngY

Code :
#include <stdio.h>
#include <conio.h>
void bubble(int n,int a[])
{ 
    int temp,i,j,k;
    for(i=0;i<n;i++)
    {
        printf("\nPass %d: ",i);
        for(k=0;k<n;k++)
        {  
            printf("%d\t",a[k]);
        }
        for(j=0;j<n;j++)
        {
            if(a[j]>a[j+1])
            {   
                temp=a[j];
                a[j]=a[j+1];
                a[j+1]=temp;
            }
        }
    }
}
void main()
{
    int i,n,a[10];
    clrscr();
    printf("Enter no. of elements : ");
    scanf("%d",&n);
    printf("Enter the elements in array : \n");
    for(i=0;i<n;i++)
    { 
        scanf("%d",&a[i]);
    } 
    bubble(n,a);//call to the function which sorts elements
    printf("\nElements after sorting\n");
    for(i=0;i<n;i++)
    {
        printf("%d\t",a[i]);
    }
    getch();
}
Output :
Enter no. of elements : 5
Enter the elements in array :
45
36
28
10
5

Pass 0: 45      36      28      10      5
Pass 1: 36      28      10      5       45
Pass 2: 28      10      5       36      45
Pass 3: 10      5       28      36      45
Pass 4: 5       10      28      36      45
Elements after sorting
5       10      28      36      45
Note : The program above has been tested using TurboCPP. Leave a comment if you feel the program is incorrect and/or has errors and/or if the program and its output don't match. Please report about broken links.

No comments:

Post a Comment