Bubble sort is the simplest sorting technique. In Bubble Sort, the adjacent elements of an array are checked successively and the elements are swapped if they are placed in the wrong order.
Also Read: Function In C Programming
PseudoCode:
Let A be the array and n be the size of the array, then the following pseudo code can be applied for Bubble Sort.
BubbleSort(A,n)
{
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(A[j]>A[j+1]
{
swap(A[j],A[j+1]);
}
}
}
}
Code in C:
#include<stdio.h>
#include<conio.h>
int BubbleSort(int [],int);
int main()
{
int a[20];
int i;
int n;
printf("How many numbers?: "); /* to ask how many numbers*/
scanf("%d",&n);
printf("\nEnter %d numbers ",n);
for(i=0;i<n;i++)
{
printf("\nEnter %dth number: ",i+1);
scanf("%d",&a[i]);
}
BubbleSort(a,n);
getch();
return(0);
}
int BubbleSort(int a[],int n)
{
int i,j;
int temp;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])/*ascending order*/ /*for decreasing order use <*/
{
/*swapping*/
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("The numbers in sorted ascending order is: \n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}
Do comment down if you are confused in any steps or if you any queries.