Program for Bubble Sort
Introduction
Hello friends, In this post, we will learn how to write a simple program in C for Bubble Sort.This tutorial is for those people who want to learn programming in C and do not necessarily have any previous knowledge of other programming languages. Of course any knowledge of other programming languages or any general computer skill can be useful to better understand this tutorial, although it is not essential.
Here we are calling two standard library functions. Whenever we call the library functions we must write their prototype before making the call.This helps the compiler in checking whether the values being passed and returned are as per the prototype declaration.But since we don’t define the library functions (we merely call them) we may not know the prototypes of library functions. Hence when the library of functions is provided a set of ‘.h’ files is also provided.These files contain the prototypes of library functions. But why multiple files? Because the library functions are divided into different groups and one file is provided for each group. For example, prototypes of all input/output functions are provided in the file ‘stdio.h’, prototypes of all mathematical functions are provided in the file ‘math.h’, etc.
On compilation of the above code the compiler reports all errors due to the mismatch between parameters in function call and their corresponding prototypes declared in the file ‘conio.h’. You can even open this file and look at the prototypes.
Program Briefing
First, we call the standard library function 'stdio.h' because prototypes of all input/output functions are provided in the file ‘stdio.h’. Then we call the standard library function 'conio.h' because On compilation of the above code the compiler reports all errors due to the mismatch between parameters in function call and their corresponding prototypes declared in the file ‘conio.h’. Then comes the program's main body. We declare two integer variables 'n' and 'i' and one array 'a'. Then we ask for the total number of values and store it in variable 'n'. Then we take all the values from user one by one and store it in the array. and call the subroutine 'bubble_sort'. Here, we compare first two values in array and if the first one is greater then shift its position to right. In this manner we compare all two values and sort them in ascending order and the print them.
//Program for Bubble Sort :Program
#include<stdio.h>
#include<conio.h>
void bubble_sort(int[],int);
void main()
{
clrscr();
int a[100],n,i;
printf("Enter the size of array\n");
scanf("%d",&n);
printf("\nEnter values\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
bubble_sort(a,n);
printf("\nSorted array is :\n");
for(i=0;i<n;i++)
{
printf("\n%d",a[i]);
}
getch();
}
void bubble_sort(int a[],int n)
{
int i,j,t;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1;j++)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
}
No comments