C Program to Implement Bubble Sort Algorithm

This program is an implementation of Bubble sort algorithm. The program receives unsorted input numbers and sorts the number in ascending or descending number as an output.

This program is written with Turbo C++ version 3 compiler, but you can use any other standard C compiler to code and run this program. It is intended for intermediate to an advanced level learner of C language.

To help you understand this program see the following sections – Problem definition, Flowchart of the program and a verified output.

Problem Definition

In this program, we read some numbers into an array. The numbers are unsorted and our goal is to sort the input numbers using Bubble Sort algorithm.

In depth analysis of the Bubble Sort algorithm is not in the scope of the article. We discuss the working of this algorithm and later implement the same using C program.

The working of this algorithm is easy to understand with an example. Suppose we are given following unsorted numbers to sort using bubble sort.

unsorted = 2 4 1 8 6

Pick the first number = 2

Compare with all the number one-by-one from right-to-left and when a[j] > a[j+1], swap the numbers.

2 < 4 (no swap)
2 > 1 (swap)
The array is now = 1 2 4 8 6

Pick the second number = 2 and it is smaller than all the other numbers.

Pick the third number = 4 and it is found to be smaller the rest of the numbers.

8 > 6 (swap)
The array is now = 1 2 3 4 6 8

Pick the fourth number = 8,

Pick the fifth number = 6 to sort and it is again smaller than last number 8. In this way the whole array is sorted.

Program Code Bubble sort

/*PROGRAM FOR BUBBLE SORTING */

#include <stdio.h>

#include <stdlib.h>

#define N 100

main()
{

int array[N],n,i,j,temp;

/* Read number of elements in array */

printf("ENTER NUMBER OF ELEMENTS:");
scanf("%d",&n);

/* Read the elements of array */

printf("ENTER %d ELEMENTS\n",n);

for(i=0;i<n;i++)
{

scanf("%d",&array[i]); }

/* Do Bubble Sort */

for(i=0;i<(n-1);i++)
{

for(j=0;j<(n-i-1);j++)
{

if(array[j]>array[j+1])
{

temp = array[j];
array[j]=array[j+1];
array[j+1] = temp;
}

}

}

/* Print the Sorted Array */

printf("_____________________________________________\n");

printf("Sorted list in Ascending Order:\n");

for(i=0;i<n;i++)
{

printf("%d\t",array[i]);

}

printf("\n____________________________________________\n");

getch();
return 0;

}

Output-Bubble Sort Algorithm

The output of the above program for bubble sort algorithm is given below. The first ask for number of elements and then the elements itself.

The output is sorted number in ascending order. You can modify the program source code to change the order.

ENTER NUMBER OF ELEMENTS:5
ENTER 5 ELEMENTS
12
33
6
2
55
________________________________________________
Sorted list in Ascending Order:
2       6       12      33       55