Sorting of array in C++

Sorting of Array in C++ Language


On this page, we will look into a coding question where we will learn how to sort the array in the C++ programming language. There are many sorting techniques to sort the array-like quick sort, merge sort, bubble sort, and insertion sort them is scripted below.
Here on this page, we are going to discuss the selection for sorting an array in C++.

Example :

  • Size : 5
  • Elements of array : 5 7 2 1 6
  • Array after sorting : 1 2 5 6 7 
sorting of array in C++

Algorithm :

  • Take the size of the array from the user.
  • Declare an array of given input size.
  • Take the input of all elements of the array.
  • Now run a for loop from 0 to size-1.
  • And for every element check it from all the next elements to it. If the element is greater than swap that number.
  • In this way the array will get sorted in ascending order.

C++ code based on above approach​


#include <bits/stdc++.h>
using namespace std;

int main()
    int n;
    cout<<"Enter the size of array: "; cin>>n;
    int a[n];
    cout<<"\nEnter the elements: ";
    for(int i=0; i<n; i++) cin>>a[i];
    for(int i=0; i<n; i++)
        for(int j=i+1; j<n; j++) { if(a[i]>a[j])
                int temp = a[i];
                a[i] = a[j];
                a[j] = temp;
    cout<<"\nArray after swapping: ";
    for(int i=0; i<n; i++)
      cout<<a[i]<<" ";
    return 0;


Enter the size of array: 5
Enter the elements: 1 3 2 5 4
Array after swapping: 1 2 3 4 5