Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

C++ program to Sort an Array in Ascending and Descending order

Sorting of array in ascending and descending order

There are lot of algorithms to sort an array efficiently. Here we are using simple algorithm to sort an array in ascending order and descending order. We select an element from an array and place it to its correct position by comparing with subsequent elements.

Example:

Input

  • size of array = 5
  • array= 4 8 6 2 9

Output

  • Ascending order = 2 4 6 8 9
  • Descending order = 9 8 6 4 2
C++ Program for Sorting of array in ascending and descending order

Algorithm:

  • 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++ Code:

#include <iostream>
using namespace std;

int main() {
    int i,j,n,a[100],temp,p,q,temp1;
    cout<<“Enter the size of array : \n;  
    cin>>n;
    cout<<“Enter the elements : \n;  
    for(i=0;i<n;i++)
    {
        cin>>a[i];
    }
    for(i=0;i<n;i++)  
    {
        for(j=i+1;j<n;j++) { if(a[i]>a[j])
            {
                temp=a[i];
                a[i]=a[j];
                a[j]=temp;
            }
        }
    }
    cout<<“Ascending order of an array : \n;  
    for(i=0;i<n;i++)
    {
        cout<<a[i]<<” “;
    }
    
    for(p=0;p<n;p++)
    {
        for(q=p+1;q<n;q++)
        {
            if(a[p]<a[q])
            {
                temp1=a[p];
                a[p]=a[q];
                a[q]=temp1;
            }
        }
    }
    cout<<\nDescending order of an array : \n;  
    for(p=0;p<n;p++)
    {
        cout<<a[p]<<” “;
    }
    return 0;
}

Input:

Enter the size of array : 5
Enter the elements : 4 8 6 2 9

Output:

Ascending order of an array : 
2 4 6 8 9 
Descending order of an array : 
9 8 6 4 2 

Python program to Sort an Array in Ascending and Descending order