The below program takes an array as an input and prints the elements of the array in sorted order. Adjacent elements are checked in this sorting method. The program is implemented using c.
#include<stdio.h>
int main()
{
int temp,i,n,j;
printf("nEnter number of elements that are to be sorted : ");
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=n-1;i>=0;i--)
for(j=1;j<=i;j++)
if(a[j-1]>a[j])
{
temp=a[j-1];
a[j-1]=a[j];
a[j]=temp;
}
printf("The elements in sorted order are :");
for(i=0;i<n;i++)
printf("%d ",a[i]);
}
Description:
The above program sorts the given array and prints it. The adjacent elements are checked whether the two elements are in sorted order or not. If the two elements are not in sorted order swapping takes place to make them sorted.
Output:
Case 1:
Enter number of elements that are to be sorted : 5
8 6 4 9 1
The elements in sorted order are :
1 4 6 8 9
8 6 4 9 1
The elements in sorted order are :
1 4 6 8 9
Case 2:
Enter number of elements that are to be sorted : 7
45 98 22 3 6 44 8
The elements in sorted order are :
3 6 8 22 44 45 98
45 98 22 3 6 44 8
The elements in sorted order are :
3 6 8 22 44 45 98

Developer, Tinkere, a proud Dad.. love to spend my available time playing with Tech!!