You are currently viewing Day 17: Sorting of numbers using array.

Day 17: Sorting of numbers using array.

Share this to everyone:

Swapping:

The process of exchanging the values of any two variable is called swapping. For example, if a=5,b=6

After swapping,

b=5, a=6

t=a; //t=5

a=b;//a=6

b=t;//b=5

Sorting:

Sorting is the process of arranging elements in a specific order, typically in ascending or descending order.

Program to input 5 numbers and display them in ascending order.

#include<stdio.h>

#include<conio.h>

void main()

{

 Clrscr();

int a[5],i,j,t;

printf(“Enter any 5 numbers\n”);

for(i=0;i<=4;i++)

{

scanf(“%d”,&a[i]);

}

for(i=0;i<=4;i++)

{

for(j=i+1;j<=4;j++)

{

if(a[i]>a[j])   

{

t=a[i];   

a[i]=a[j];

a[j]=t;

}

}

}

printf(“the numbers in ascending order are\n”);

for(i=0;i<=4;i++)

{

printf(“%d\t”,a[i]);

}

getch();

}

Initial Array: 5, 4, 3, 2, 1

a[0]=5, a[1]=4, a[2]=3, a[3]=2, a[4]=1

Iteration 1 (i=0):

Inner Loop (j=1): Compare 5 and 4, swap (4, 5, 3, 2, 1)

Inner Loop (j=2): Compare 5 and 3, swap (4, 3, 5, 2, 1)

Inner Loop (j=3): Compare 5 and 2, swap (4, 3, 2, 5, 1)

Inner Loop (j=4): Compare 5 and 1, swap (4, 3, 2, 1, 5)

Array after iteration 1:

 4, 3, 2, 1, 5

Iteration 2 (i=1):

Inner Loop (j=2): Compare 4 and 3, swap (3, 4, 2, 1, 5)

Inner Loop (j=3): Compare 4 and 2, swap (3, 2, 4, 1, 5)

Inner Loop (j=4): Compare 4 and 1, swap (3, 2, 1, 4, 5)

Array after iteration 2:

3, 2, 1, 4, 5

Iteration 3 (i=2):

Inner Loop (j=3): Compare 3 and 2, swap (2, 3, 1, 4, 5)

Inner Loop (j=4): Compare 3 and 1, swap (2, 1, 3, 4, 5)

Array after iteration 3:

2, 1, 3, 4, 5

Iteration 4 (i=3):

Inner Loop (j=4):

 Compare 2 and 1, swap (1, 2, 3, 4, 5)

Array after iteration 4:

1, 2, 3, 4, 5

Final Array:

1, 2, 3, 4, 5

Program to input 5 numbers and display them in descending order.

#include<stdio.h>

#include<conio.h>

void main()

{

 Clrscr();

int a[5],i,j,t;

printf(“Enter any 5 numbers\n”);

for(i=0;i<=4;i++)

{

scanf(“%d”,&a[i]);

}

for(i=0;i<=4;i++)

{

for(j=i+1;j<=4;j++)

{

if(a[i]<a[j])

{

t=a[i];

a[i]=a[j];

a[j]=t;

}

}

}

printf(“the numbers in descending order are\n”);

for(i=0;i<=4;i++)

{

printf(“%d\t”,a[i]);

}

getch();

}