Home »
C++ programs »
C++ Most popular & searched programs
C++ program to sort an array in Ascending Order
Given an integer array, we have to sort it in an ascending order using C++ program.
[Last updated : February 27, 2023]
Sorting an array in Ascending Order
In this program, we will learn how to sort integer array numbers/elements in Ascending Order in C++?
This program will read total number of elements (N) and check value of N must be valid between 1-N, program will read N integer values (as array elements), print input elements with sorted array element (After sorting elements in Ascending Order).
C++ program to sort an array in Ascending Order
#include <iostream>
using namespace std;
#define MAX 100
int main()
{
//array declaration
int arr[MAX];
int n, i, j;
int temp;
//read total number of elements to read
cout << "Enter total number of elements to read: ";
cin >> n;
//check bound
if (n < 0 || n > MAX) {
cout << "Input valid range!!!" << endl;
return -1;
}
//read n elements
for (i = 0; i < n; i++) {
cout << "Enter element [" << i + 1 << "] ";
cin >> arr[i];
}
//print input elements
cout << "Unsorted Array elements:" << endl;
for (i = 0; i < n; i++)
cout << arr[i] << "\t";
cout << endl;
//sorting - ASCENDING ORDER
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
//print sorted array elements
cout << "Sorted (Ascending Order) Array elements:" << endl;
for (i = 0; i < n; i++)
cout << arr[i] << "\t";
cout << endl;
return 0;
}
Output
First run:
Enter total number of elements to read: 5
Enter element [1] 123
Enter element [2] 345
Enter element [3] 567
Enter element [4] 12
Enter element [5] 90
Unsorted Array elements:
123 345 567 12 90
Sorted (Ascending Order) Array elements:
12 90 123 345 567
Second run:
Enter total number of elements to read: 120
Input valid range!!!