C++ Program to sort an array in ascending order


In this program, You will learn how to sort an array in ascending order in C++.


List is: 1, 4, 5, 2, 3, 6

After sort: 1, 2, 3, 4, 5, 6

Example: How to sort an array in ascending order in C++.

#include<iostream>
using namespace std;

int main() {

    int a[10];
    int n, temp;

    cout << "Enter size of an array:";
    cin>>n;

    cout << "Enter array elements:";
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }

    for (int i = 0; i < n; i++) {
        for (int j = 1 + i; j < n; j++) {
            if (a[i] > a[j]) {
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }
    cout << "Array list after sorting:";
    for (int i = 0; i < n; i++) {
        cout << a[i] << " ";
    }

    return 0;
}

Output:

Enter size of an array:5
Enter array elements:10 30 20 50 40
Array list after sorting:10 20 30 40 50 

Xiith is created for educational, experimental, and schooling purpose. Examples on Xiith are made easier to make a better or basic understanding. Tutorials, testimonials, and examples are continuously checked to avoid delusion, but we cannot take complete responsibility of all programs on Xiith. When you are operating this site, you have to agree to read and accept our terms of use, cookie and privacy policy.Copyright © 2020 by Xiith. All Rights Reserved. About us.