C Program to Implement Bubble Sort Algorithm

Previous Article
Next Article
This program is an implementation of Bubble sort algorithm. The program receives unsorted input numbers and sort 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 advanced level learner of C language.
To help you understand this program see 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.
Pick the fourth number = 8,
8>6 (swap)
The array is now = 1 2 3 4 6 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


#include <stdio.h>
#include <conio.h>
#define N 100 main() {
int array[N],n,i,j,temp;
/* Read number of elements in array */
/* Read the elements of array */
printf("ENTER %d ELEMENTS\n",n);
for(i=0;i<n;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+1] = temp;
/* Print the Sorted Array */
printf("Sorted list in Ascending Order:\n");
for(i=0;i<n;i++) {
return 0;


Output-Bubble Sort


Previous Article
Next Article