Sort the array in ascending order
C program to sort the array in ascending order.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
void read_array(int a[MAX], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Element %d\t:",i+1);
scanf("%d",&a[i]);
}
}
void print_array(int a[MAX], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Element %d\t:%d\n",i+1,a[i]);
}
}
void main()
{
int arr[MAX];
int i, j, n, temp;
printf("Enter the number of elements in the array\t:");
scanf("%d",&n);
printf("Enter the elements of the array\n");
read_array(arr, n);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
printf("\nSorted array in ascending order is\n");
print_array(arr, n);
getch();
}
Output
Enter the number of elements in the array :8
Enter the elements of the array
Element 1 :56
Element 2 :89
Element 3 :96
Element 4 :12
Element 5 :45
Element 6 :32
Element 7 :58
Element 8 :78
Sorted array in ascending order is
Element 1 :12
Element 2 :32
Element 3 :45
Element 4 :56
Element 5 :58
Element 6 :78
Element 7 :89
Element 8 :96