C program to sort an array in ascending and descending order

C program to sort an array in ascending and descending order

Today we will learn how to sort an array in ascending and descending manner.There are numerous logic to sort an array elements. Here we will using general algorithm, we select an element from an array and place it to its correct position by comparing with subsequent elements.
For Example:
Input :- From the user {4,3,6,1,8}
Output :- In ascending order {1,3,4,6,8} and In descending order {8,6,4,3,1}.

Sorting of array in ascending and descending order

Implementation:-

  • Input size of array.
  • Store it in some variable say n and a[].
  • To select each element from array, run an outer loop from 0 to n-1.
  • Run another inner loop from i + 1 to n – 1 to place newly selected element at its correct position.
  • Inside inner loop to compare currently selected element with subsequent element and swap two array elements, if not placed at its correct position.
  • C program to sort array in ascending or descending order
    Competitive Coding Techniques

    C Code:-

    //C Program to sort an array in ascending or descending order
    #include 
    void  main()
    {
        int i,j,n,a[100],temp,p,q,temp1;
        printf("Enter the size of array : \n") ;  //Taking size of array
        scanf("%d",&n) ;
        printf("Enter the elements : \n") ;  //Taking input from user
        for(i=0;i<n;i++)
        {
            scanf("%d",&a[i]) ;
        }
        for(i=0;i<n;i++)  // loop for sorting array in ascending order
        {
            for(j=i+1;j<n;j++) { if(a[i]>a[j])
                {
                    temp=a[i];
                    a[i]=a[j];
                    a[j]=temp;
                }
            }
        }
        printf("Ascending order of an array : \n");  //print ascending order
        for(i=0;i<n;i++)
        {
            printf("%d ",a[i]) ;
        }
        
        for(p=0;p<n;p++) // loop for sorting array in descending order
        {
            for(q=p+1;q<n;q++)
            {
                if(a[p]<a[q])
                {
                    temp1=a[p];
                    a[p]=a[q];
                    a[q]=temp1;
                }
            }
        }
        printf("\n Descending order of an array : \n");  // print descending order
        for(p=0;p<n;p++)
        {
            printf("%d ",a[p]) ;
        }
    }
    Output:-
    Enter the size of array :
    5
    Enter the elements :
    9
    5
    1
    2
    7
    Ascending order of an array :
    1 2 5 7 9
    Descending order of an array :
    9 7 5 2 1



    //test case 2
    Enter the size of array : 5 Enter the elements : 9 5 1 2 7 Ascending order of an array : 1 2 5 7 9 Descending order of an array : 9 7 5 2 1

    //test case 3
    Enter the size of array : 5 Enter the elements : 9 5 1 2 7 Ascending order of an array : 1 2 5 7 9 Descending order of an array : 9 7 5 2 1
    Competitive Coding Techniques