Showing posts with label Program to sort an array in ascending and descending order. Show all posts
Showing posts with label Program to sort an array in ascending and descending order. Show all posts

Wednesday, July 20, 2011

Program to sort an array in ascending and descending order

/*Serial No.95     [swami70.cpp]*/

#include<stdio.h>
#include<conio.h>
void main()
    {
    int a[5],i,j,k,temp=0;
    clrscr();
    printf("How many numbers you want to store:=");
    scanf("%d",&k);
    printf("Enter numbers for in an array:=");
    for(i=0;i<k;i++)
       {
       scanf("%d",&a[i]);
       }
    for(i=1;i<k;i++)
       {
       for(j=1;j<k;j++)
          {
          if(a[j]>a[j-1])  //NOTE: we can simply replace '<' by '>' for ascending order.
         {
         temp=a[j-1];
         a[j-1]=a[j];
         a[j]=temp;
         }
          }
       }
    printf("The sorted array in descending order is:=\n");
    for(i=0;i<k;i++)
        {
        printf("\t%d",a[i]);
        }
    printf("\n\nThe sorted array in ascending order is:=\n");
    for(i=k-1;i>=0;i--)
        {
        printf("\t%d",a[i]);
        }
    getch();
    }