In this tutorial you will learn about the C Program to implement Bubble sort Algorithm and its application with practical example.
C Program to implement Bubble sort Algorithm
In this tutorial, we will learn to create a C program that will do Bubble sort using C programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- For loop in C Programming.
- Creating and Using the user-defined function in C programming.
What is Bubble Sort?
In every programming language, the sorting of data is a very important factor. In C Language. Many different techniques for sorting are available to work with but in this tutorial, we will focus on the Bubble Sort Technique.
In this technique, the elements of the array are sorted from the very first value by swapping from starts first & second and going to till the end. Now, this process will go on until the array is completely arranged.
Algorithm for optimized bubble sort
1 2 3 4 5 6 7 8 9 10 11 12 13 |
bubbleSort(array) n = length(array) repeat swapped = false for i = 1 to n - 1 if array[i - 1] > array[i], then swap(array[i - 1], array[i]) swapped = true end if end for n = n - 1 until not swapped end bubbleSort |
Program For Bubble Sort
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
#include<stdio.h> void print(int x[], int no) //function to print elements of array { int i; for(i = 0; i < no; i++) { printf("%d ",x[i]); } } void bubble(int x[], int no) // function for implement bubble sort { int i, j, flag; for(i = 0; i < no; i++) { for(j = i+1; j < no; j++) { if(x[j] < x[i]) { flag = x[i]; x[i] = x[j]; x[j] = flag; } } } } void main () { int i, j,flag; int x[5] = { 78, 69, 13, 96, 95}; int no = sizeof(x)/sizeof(x[0]); printf("Before sorting elements of array - \n"); print(x, no); bubble(x, no); printf("\nAfter sorting elements of array- \n"); print(x, no); } |
Output :-
In the above program, we have first declared and initialized a set variables required in the program.
- no = it will hold the size of the array.
- x[5]= it will hold the elements in an array.
- flag= it will hold the temporary values.
- i= it will hold the integer value to control the array.
- j= it will hold the integer value to control the array.
Function to print on the terminal/console.
Function to implement the bubble sort.
The main function to perform and navigate the program cleanly.