The following program shows how to sort a linear array in ascending order of any size. You can sort the same array in descending order from the same logic. This type of sorting is also called linear sort.
Output:
How many number : 5
Enter 5 number:
5
4
2
3
9
Number in ascending order:
2 3 4 5 9
array_sort.c
#include <stdio.h>
#include <conio.h>
void main(){
int arr[100], temp, n, i, j;
printf("How many number: ");
//get number for array size
scanf("%d", &n);
printf("Enter %d number : ", n);
for(i = 0; i < n; i++)
{
//get number for array
scanf("%d", &arr[i]);
}
//sort in ascending order
for(i = 0; i < n; i++)
{
for(j = i+1; j < n; j++)
{
if(arr[i] > arr[j])
{
//swaping
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
//display sorted array
printf("Number in ascending order \n");
for(i = 0; i < n; i++)
{
printf("%d \t", arr[i]);
}
getch();
}
#include <stdio.h>
#include <conio.h>
void main(){
int arr[100], temp, n, i, j;
printf("How many number: ");
//get number for array size
scanf("%d", &n);
printf("Enter %d number : ", n);
for(i = 0; i < n; i++)
{
//get number for array
scanf("%d", &arr[i]);
}
//sort in ascending order
for(i = 0; i < n; i++)
{
for(j = i+1; j < n; j++)
{
if(arr[i] > arr[j])
{
//swaping
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
//display sorted array
printf("Number in ascending order \n");
for(i = 0; i < n; i++)
{
printf("%d \t", arr[i]);
}
getch();
}
Output:
How many number : 5
Enter 5 number:
5
4
2
3
9
Number in ascending order:
2 3 4 5 9
No comments:
Post a Comment