C program to sort array elements using Bubble sort

Posted on 20th April 2015

Bubble sort is a simple but less efficient sorting algorithm to sort the elements of an array in ascending or descending order.

Bubble sort starts by comparing the first and second element of the array and swaps their positions if necessary (depending on whether the sort order is ascending or descending). Next, it will compare the second and third element and swaps them if needed. This is continued upto the last element of the array and then the iteration starts again from the first element to last. If no elements are swapped in an iteration then it means the array is fully sorted and the iteration ends. Each iteration or pass of bubble sort from first to last element will move one element to its correct location in the array just like a bubble rising up in water.

An example of bubble sorting is depicted in the figure below:

Here is a C program that takes the elements of an array as input, sort it using bubble sort algorithm and prints the sorted array.

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

int main()
{
int myarray;
int i, n, temp, swapflag;

/* Get the number of items in array */
printf("How many items are in the array? \n");
scanf("%d", &n);

printf("Enter the array items \n");
for (i = 0; i < n; i++)
scanf("%d", &myarray[i]);

/* Sort array using bubble sort method */
do {
swapflag = 0;
for (i = 0; i < n-1; i++) {
if (myarray[i] > myarray[i+1]) {
temp = myarray[i+1]
myarray[i+1] = myarray[i];
myarray[i] = temp;
swapflag = 1;
}
}
} while (swapflag == 1);

/* Print the sorted array */
printf("Array items sorted in ascending order \n");
for (i = 0; i < n; i++)
printf("%d \n", myarray[i]);

getch();
return 0;

}