C program to sort the elements of an array in ascending order
This C program is to sort the elements of an array in ascending order.For example, if an array a consists of elements a={7,8,12,3} , then on sorting in ascending order we would get a={3,7,8,12}.
Logic
We use two for loops, the outer for loop for traversing all the elements and the inner(nested) for loop for comparing the element with all of the inner elements and then performing swap operation
Dry Run of the Program
Take input array ‘a’ and no of elements(n) as 4
Let us take elements for array a={7,8,12,3}.
1st iteration for(i=0;i<n;i++) i.e. for(i=0;0<4;i++) – Outer for loop
1st iteration for(j=i+1;j<n;j++) i.e. for(j=1;1<4;j++) – Inner for loop
if(a[i]>a[j]) i.e. if(a[0]>a[1]) i.e. if(7>8) false
2nd iteration for(j=i+1;j<n;j++) i.e. for(j=2;2<4;j++) – Inner for loop
if(a[i]>a[j]) i.e. if(a[0]>a[1]) i.e. if(7>12) false
3rd iteration for(j=i+1;j<n;j++) i.e. for(j=3;3<4;j++) – Inner for loop
if(a[i]>a[j]) i.e. if(a[0]>a[1]) i.e. if(7>3) true
temp=a[i]; i.e. temp=a[0] i.e. temp=7
a[i]=a[j]; i.e. a[0]=a[3] i.e. a[0]=3
a[j]=temp; i.e. a[3]=7
So now are array is a={3,8,12,7}
2nd iteration for(i=1;i<n;i++) i.e. for(i=1;1<4;i++) – Outer for loop
1st iteration for(j=i+1;j<n;j++) i.e. for(j=2;2<4;j++) – Inner for loop
if(a[i]>a[j]) i.e. if(a[1]>a[2]) i.e. if(8>12) false
2nd iteration for(j=i+1;j<n;j++) i.e. for(j=2;2<4;j++) – Inner for loop
if(a[i]>a[j]) i.e. if(a[1]>a[3]) i.e. if(8>7) true
temp=a[i]; i.e. temp=a[1] i.e. temp=8
a[i]=a[j]; i.e. a[1]=a[3] i.e. a[1]=7
a[j]=temp; i.e. a[3]=8
So now are array is a={3,7,12,8}
3rd iteration for(i=2;i<n;i++) i.e. for(i=2;2<4;i++) – Outer for loop
1st iteration for(j=i+1;j<n;j++) i.e. for(j=3;3<4;j++) – Inner for loop
if(a[i]>a[j]) i.e. if(a[2]>a[3]) i.e. if(12>8) true
temp=a[i]; i.e. temp=a[2] i.e. temp=12
a[i]=a[j]; i.e. a[2]=a[3] i.e. a[2]=8
a[j]=temp; i.e. a[3]=12
So now are array is a={3,7,8,12}
Hence we have sorted the elements in ascending order a={3,7,8,12}.
Program
#include<stdio.h> void main() { int i,j,n,a[100],temp; printf("Enter the number of elements:\n") ; scanf("%d",&n) ; printf("Enter the elements\n") ; for(i=0;i<n;i++) { scanf("%d",&a[i]) ; } for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(a[i]>a[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } printf("Elements sorted in ascending order are\n"); for(i=0;i<n;i++) { printf("%d ",a[i]) ; } }