// Write a program to rea n integer numbers in an array dynamically
// and create two functions to sort in ascending and descending order
// and display the result in the main function.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void ascending(int*, int);
void descending(int*, int);
void main()
{
int *ptr,n,i;
printf("Enter n: ");
scanf("%d",&n);
ptr = (int*)malloc(n*sizeof(int));
printf("Enter the elements:\n");
for(i=0;i<n;i++)
{
scanf("%d",(ptr+i));
}
ascending(ptr,n);
printf("Ascending order: \n");
for(i=0;i<n;i++)
{
printf("%d ",*(ptr+i));
}
descending(ptr,n);
printf("\nDescending order: \n");
for(i=0;i<n;i++)
{
printf("%d ",*(ptr+i));
}
getch();
}
void ascending(int *ptr, int n)
{
int i,temp;
while(n!=0)
{
for(i=0;i<n-1;i++)
{
if(*(ptr+i) > *(ptr+i+1))
{
temp=*(ptr+i);
*(ptr+i)=*(ptr+i+1);
*(ptr+i+1)=temp;
}
}
n--;
}
}
void descending(int *ptr, int n)
{
int i,temp;
while(n!=0)
{
for(i=0;i<n-1;i++)
{
if(*(ptr+i) < *(ptr+i+1))
{
temp=*(ptr+i);
*(ptr+i)=*(ptr+i+1);
*(ptr+i+1)=temp;
}
}
n--;
}
Output:
No comments:
Post a Comment