Sort array in Ascending and Descending Order:C Program

0
4493

 To sort given array in ascending order

Ascending order: Arrange from smallest to largest….Increasing……

[message_box title=”Program” color=”yellow”]

/* Write a program to sort given array in ascending order */

/* Written by Utpal Chaudhary  */

/* Student of L.D COLLEGE OF ENGINEERING,Ahmedabad-15,Gujarat */

#include <stdio.h>
#include <conio.h>
void main()
{
int a[10], i=0, j=0, n, t;
clrscr();

printf (“\n Enter the no. of elements: “);
scanf (“%d”, &n);
printf (“\n”);

for (i = 0; i <n; i++)
{
printf (“\n Enter the %d element: “, (i+1));
scanf (“%d”, &a[i]);
}

for (j=0 ; j<(n-1) ; j++)
{
for (i=0 ; i<(n-1) ; i++)
{
if (a[i+1] < a[i])
{
t = a[i];
a[i] = a[i + 1];
a[i + 1] = t;
}
}
}

printf (“\n Ascending order: “);
for (i=0 ; i<n ; i++)
{
printf (” %d”, a[i]);
}
/* indicate successful completion */
getch();
}
[/message_box]

[message_box title=”Output” color=”yellow”]

Enter the no. of elements:5

Enter the 1 element:12

Enter the 2 element:4

Enter the 3 element:45

Enter the 4 element:30

Enter the 5 element:15

Ascending order: 4  12  15  30  45

[/message_box]

To sort given array in descending order

Descending order: Arrange from largest to smallest….Decreasing……

[message_box title=”Program” color=”yellow”]

/* Write a program to sort given array in descending order */

/* Written by Utpal Chaudhary  */

/* Student of L.D COLLEGE OF ENGINEERING,Ahmedabad-15,Gujarat */

#include <stdio.h>
#include <conio.h>
void main()
{
int a[10], i=0, j=0, n, t;
clrscr();

printf (“\n Enter the no. of elements: “);
scanf (“%d”, &n);
printf (“\n”);

for (i = 0; i <n; i++)
{
printf (“\n Enter the %d element: “, (i+1));
scanf (“%d”, &a[i]);
}

for (j=0 ; j<(n-1) ; j++)
{
for (i=0 ; i<(n-1) ; i++)
{
if (a[i+1] < a[i])
{
t = a[i];
a[i] = a[i + 1];
a[i + 1] = t;
}
}
}

printf (“\n Descending order: “);
for (i=n ; i>0 ; i–)
{
printf (” %d”, a[i-1]);
}

/* indicate successful completion */
getch();
}

[/message_box]

[message_box title=”Output” color=”yellow”]

Enter the no. of elements:5

Enter the 1 element:12

Enter the 2 element:4

Enter the 3 element:45

Enter the 4 element:30

Enter the 5 element:15

Ascending order: 45  30  15  12  4

[/message_box]