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++.

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

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription