C++ - Sorting Numbers
C++ program for sorting numbers in ascending order is given on this page. This program will accept the number of elements as first input. Then it will use the for loop to input the elements list.
Two nested for loops are used for sorting in ascending order. If you need decending order program, then change the if condition from > to <.
Source Code
#include <stdio.h>
#include <string>
// Program for ascending order of Numeric Values
int main()
{
int max;
std::cout << "\nProgram for Ascending order of Numeric Values";
std::cout << "\n\nEnter the total number of elements: ";
std::cin >> max;
std::cout << "\n
int *numarray = new int[max];
for(int i = 0; i < max; i++)
{
std::cout << "Enter [" << i + 1 << "] element: ";
std::cin >> numarray[i];
}
for(int i = 0; i < max; i++)
{
for(int j = 0; j < max; j++)
{
if(numarray[i] < numarray[j])
{
int temp = numarray[i];
numarray[i] = numarray[j];
numarray[j] = temp;
}
}
}
std::cout << "\n\nThe numbers in ascending orders are given below:\n\n";
for(int i = 0; i < max; i++)
{
std::cout << "Sorted [" << i + 1 << "] element: ";
std::cout << numarray[i];
std::cout << "\n";
}
delete [] numarray;
return 0;
}
Output
Program for Ascending order of Numeric Values
Enter the total number of elements: 5
Enter [1] element: 200
Enter [2] element: 400
Enter [3] element: 100
Enter [4] element: 500
Enter [5] element: 300
The numbers in ascending orders are given below:
Sorted [1] element: 100
Sorted [2] element: 200
Sorted [3] element: 300
Sorted [4] element: 400
Sorted [5] element: 500
|