Bubble Sort Program is the Simplest Sorting in C

Views: 807
Comments: 0
Like/Unlike: 0
Posted On: 11-Nov-2017 03:38 

Share:   fb twitter linkedin
reena
122 Points
12 Posts

Introduction

Bubble Sort is the simplest sorting algorithm that can be done by repeatedly swapping the adjacent elements if they are in wrong order.  It is named as bubble sort since it looks like bubbles the lighter elements come up and heavier elements settle down.

Algorithm

Step 1: Repeat Steps 2 and 3 for i=1 to 10
 
Step 2: Set j=1
 
Step 3: Repeat while j<=n
 
         (A) if  a[i] < a[j]
 
             Then interchange a[i] and a[j]
 
             [End of if]
 
         (B) Set j = j+1
        [End of Inner Loop]
 
    [End of Step 1 Outer Loop]
 
Step 4: Exit

Complexity O(n2)

C Program

//C program Bubble Sort Program

#include <stdio.h>
#include <conio.h>

int main()
{
    int a[50],n,i,j,temp;
    printf("Enter the size of array: ");
    scanf("%d",&n);
    printf("Enter the array elements: ");

    for(i=0;i<n;++i)
        scanf("%d",&a[i]);

    for(i=1;i<n;++i)
        for(j=0;j<(n-i);++j)
            if(a[j]>a[j+1])
            {
                temp=a[j];
                a[j]=a[j+1];
                a[j+1]=temp;
            }

    printf("\nArray after sorting: ");
    for(i=0;i<n;++i)
        printf("%d ",a[i]);
    getch();

    return 0;
}

Output

0 Comments
 Log In to Chat