PROGRAM - 10
Write a program to perform the following:
a) Bubble Sort.
b) Selection Sort.
c) Insertion Sort.
Program for Bubble Sort:
#include<stdio.h>
#include<conio.h>
main()
{
int a[50],i,j,n,temp;
clrscr();
printf("enter the number");
scanf("%d",&n);
printf("enter the elements into the array\n");
for(i=0;i<n;i++)
{
printf("enter the %d element",i+1);
scanf("%d",&a[i]);
}
for(i=n-1;i>=0;i--)
{
for(j=0;j<i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
printf("the numbers in the sorted order is\n");
for(i=0;i<n;i++)
{
printf("\t%d",a[i]);
}
getch();
}
/*
INPUT:enter the range5
enter the elements into the array
enter the 1 element5
enter the 2 element2
enter the 3 element4
enter the 4 element9
enter the 5 element1
OUTPUT:
the numbers in the sorted order is
1 2 4 5 9 */
Program for Selection sort:
#include<stdio.h>
#include<conio.h>
main()
{
int a[50],i,j,n,temp;
clrscr();
printf("enter the range ");
scanf("%d",&n);
printf("enter the elements into array");
for(i=0;i<n;i++)
{
printf("\nenter the %d element ",i+1);
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[j];
a[j]=a[i];
a[i]=temp;
}
}
}
printf("the elements in sorted order is\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
getch();
}
/*
INPUT:enter the range 10
enter the elements into array
enter the 1 element 95
enter the 2 element 90
enter the 3 element 85
enter the 4 element 80
enter the 5 element 75
enter the 6 element 70
enter the 7 element 65
enter the 8 element 60
enter the 9 element 55
enter the 10 element 50
the elements in sorted order is
50 55 60 65 70 75 80 85 90 95
*/
Program for Insertion sort:
#include<stdio.h>
#include<conio.h>
main()
{
int i,j,item,a[50],n;
clrscr();
printf("enter the range ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter the %d element",i+1);
scanf("%d",&a[i]);
}
for(j=1;j<n;j++)
{
item=a[j];
i=j-1;
while(i>=0&&item<a[i])
{
a[i+1]=a[i];
i=i-1;
}
a[i+1]=item;
}
printf("the elements in sorted order is\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
getch();
}
/*
INPUT:enter the range 10
enter the 1 element15
enter the 2 element24
enter the 3 element23
enter the 4 element14
enter the 5 element2
enter the 6 element6
enter the 7 element7
enter the 8 element1
enter the 9 element22
enter the 10 element10
OUTPUT:
the elements in sorted order is
1 2 6 7 10 14 15 22 23 24
*/
No comments:
Post a Comment