BUBBLE SORT :
Bubble sort is one of the simple sorting algorithm that sometimes referred to as sinking sort.
It compares each pair of adjacent element and swaps them if they are in wrong order.
9 3 6 7 1 5
Pass 1:
9 3 6 7 1 5 arr[0] > arr[1], Exchange
3 9 6 7 1 5 arr[1] > arr[2], Exchange
3 6 9 7 1 5 arr[2] > arr[3], Exchange
3 6 7 9 1 5 arr[3]> arr[4], Exchange
3 6 7 1 9 5 arr[4]> arr[5], Exchange
3 6 7 1 5 9
Pass 2:
3 6 7 1 5 9 arr[0] < arr[1]
3 6 7 1 5 9 arr[1] < arr[2]
3 6 7 1 5 9 arr[2] > arr[3], Exchange
3 6 1 7 5 9 arr[3] > arr[4], Exchange
3 6 1 5 7 9
Pass 3:
3 6 1 5 7 9 arr[0] < arr[1]
3 6 1 5 7 9 arr[1] > arr[2], Exchange
3 1 6 5 7 9 arr[2] > arr[3], Exchange
3 1 5 6 7 9
Pass 4:
3 1 5 6 7 9 arr[0] > arr[1], Exchange
1 3 5 6 7 9 arr[1] < arr[2]
1 3 5 6 7 9
Pass 5:
1 3 5 6 7 9 arr[0] < arr[1]
1 3 5 6 7 9
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[50],i,j,n,temp;
clrscr();
printf("Enter how many number you want to display: ");
scanf("%d",&n);
printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("\nElements before sorted are: \n");
for(i=0;i<n;i++)
{
printf("%d\t",arr[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
printf("\nElements after sorted are: \n");
for(i=0;i<n;i++)
{
printf("%d\t",arr[i]);
}
getch();
}
Output :
Bubble sort is one of the simple sorting algorithm that sometimes referred to as sinking sort.
It compares each pair of adjacent element and swaps them if they are in wrong order.
Let us take an unsorted list of elements and sort them by applying this algorithm.
Elements of the array -
9 3 6 7 1 5
Pass 1:
9 3 6 7 1 5 arr[0] > arr[1], Exchange
3 9 6 7 1 5 arr[1] > arr[2], Exchange
3 6 9 7 1 5 arr[2] > arr[3], Exchange
3 6 7 9 1 5 arr[3]> arr[4], Exchange
3 6 7 1 9 5 arr[4]> arr[5], Exchange
3 6 7 1 5 9
Pass 2:
3 6 7 1 5 9 arr[0] < arr[1]
3 6 7 1 5 9 arr[1] < arr[2]
3 6 7 1 5 9 arr[2] > arr[3], Exchange
3 6 1 7 5 9 arr[3] > arr[4], Exchange
3 6 1 5 7 9
Pass 3:
3 6 1 5 7 9 arr[0] < arr[1]
3 6 1 5 7 9 arr[1] > arr[2], Exchange
3 1 6 5 7 9 arr[2] > arr[3], Exchange
3 1 5 6 7 9
Pass 4:
3 1 5 6 7 9 arr[0] > arr[1], Exchange
1 3 5 6 7 9 arr[1] < arr[2]
1 3 5 6 7 9
Pass 5:
1 3 5 6 7 9 arr[0] < arr[1]
1 3 5 6 7 9
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[50],i,j,n,temp;
clrscr();
printf("Enter how many number you want to display: ");
scanf("%d",&n);
printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("\nElements before sorted are: \n");
for(i=0;i<n;i++)
{
printf("%d\t",arr[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
printf("\nElements after sorted are: \n");
for(i=0;i<n;i++)
{
printf("%d\t",arr[i]);
}
getch();
}
Output :
Comments
Post a Comment