# Sorting of array in C++

## Sorting of Array in C++ Language

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

Example :

Size : 5

Elements of array : 5 7 2 1 6

Array after sorting : 1 2 5 6 7 ## 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;        cout<<"\nEnter the elements :";    for(int i=0; i<n; i++)      cin>>a[i];                for(i=0; i<n; i++)    {        for(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(i=0; i<n; i++)      cout<<a[i]<<" ";          return 0;}`
`Output :Enter the size of array : 5Enter the elements : 7 2 1 5 4Array after swapping : 1 2 4 5 7`