Video courses for company/skill based Preparation
Purchase mock tests for company/skill building
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.
- size of array = 5
- array= 4 8 6 2 9
- Ascending order = 2 4 6 8 9
- Descending order = 9 8 6 4 2
- 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.
Enter the size of array : 5 Enter the elements : 4 8 6 2 9
Ascending order of an array : 2 4 6 8 9 Descending order of an array : 9 8 6 4 2