sorting involves to systematically rearrange the data. that data may include numbers alphabets but here I am going to sort the data which involves numbers we can also apply the same method with the alphabets also.
So here is my first program to sort the numbers using selection sort:
/* SELECTION sort implementation */
void main(){ int a[5]={44,33,55,22,11},k,j,temp; clrscr();
for(k=0;k<5;k++) { for(j=k+1;j<5;j++) {
if(a[k]>a[j]) { temp=a[j]; a[j]=a[k]; a[k]=temp;
}
}
} for(j=0;j<5;j++) { printf("%d\n",a[j]); }
getch();
}
In selection sort we select the first which is 0th element and check it with other elements that weather it is greater than it or not if true then it will swap it with the next element this process will continue as soon as all the elements will not be sort.
BUBBLE SORT:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5]={44,33,55,22,11},i,k,j=0,t=0;
clrscr();
for(k=0;k<4;k++)
{
for(i=0,j=1;i<4;j++,i++)
{
if(a[i]>a[j])
{
t=a[j];
a[j]=a[i];
a[i]=t;
}
}
}
for(i=0;i<5;i++)
{
printf("%d\n",a[i]);
}
getch();
}
In bubble sort we will check the next element started from first element and this process will go on untill all the elements will be sorted.
INSERTION SORT:
/* INSERTION sort implementation */
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5]={44,33,55,22,11},i,k,t;
clrscr();
for(k=1;k<5;k++)
{
for(i=0;i<k;i++)
{
if(a[k]<a[i])
{
t=a[i];
a[i]=a[k];
a[k]=t;
}
}
}
for(i=0;i<5;i++)
{
printf("%d\n",a[i]);
}
getch();
}
No comments:
Post a Comment