c-programming-bubble-shot-banner-image (1)

C Program-To Sort Elements Using Bubble Sort


Code Description

This is a simple sorting algorithm.  In this algorithm each element is compared with adjacent element and swapped if their position is incorrect. This algorithm is named as bubble sort because after every pass the largest element moves to the end of the array same as like bubbles, the lighter elements come up and heavier elements settle down.

Example: In each step, elements written in bold are being compared.
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 the 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 )

Note: Before jumping into the source code below we would like to mention that our main goal is to provide you a good packaged solution under one umbrella.Refer to other examples of “C Programming”. For all the possible “C programming questions” which might you have faced in interviews or any other assignments or projects. If you are not able to find the desired solution, please drop us comments so that we can get back to you to with some more and more beautiful programs.You can also check out our ebook below by clicking the image anywhere which will help you for further practice and quick learning.

Note: Currently discounts are going on in our books!

 

c programming array functions and string

Source Code

//  Created by Kaustav Ghosh Dastidar.
#include <stdio.h>
int main()
{
    int a[100],i,n,step,temp;
    printf("Enter the size of the array element: ");
    scanf("%d",&n);
    printf("%d. Enter the array elements: ",i+1);
    scanf("%d",&a[i]);
    for(step=0;step<n-1;++step)
    for(i=0;i<n-step-1;++i)
    {
        if(a[i]>a[i+1])   /* Change > to < in this line, if you want to sort in descending order, */
        {
            temp=a[i];
            a[i]=a[i+1];
            a[i+1]=temp;
        }
    }
    printf("In ascending order: ");
    for(i=0;i<n;++i)
         printf("%d  ",a[i]);
    return 0;
}

Output

Enter the size of the array element: 5 
1. Enter the array elements: 5 1 4 2 8 
In ascending order: 1 2 4 5 8 

 

One Response

Add a Comment

Your email address will not be published. Required fields are marked *