# Sort an array and remove the duplicate elements in C++

In this article, we are going to learn how to sort an array and remove the duplicate elements in C++. We first get the array size and the array elements from the user. As we want the output, after removing the duplicate elements to be in sorted order, we sort the array using bubble sort in the starting itself. This algorithm takes a time complexity of O(n^2).

After sorting, we compare each element with all other elements in the array. If the element is equal to any other element then shift all the elements to the left by one place. The process is repeated until all the elements are compared.

## Sort an array and remove the duplicate elements in C++

Let’s take the help of an example.

Input: 3,2,3,4,1

Output: 1,2,3,4

As you can see, the output is in sorted order and has the duplicate elements removed.

Code Implementation:

```#include<iostream>
using namespace std;

int main()
{
int i,j,k,n,a[n],temp,pass=0;
cout<<"How many elements?";
cin>>n;
cout<<"\nEnter elements of array\n";

for(i=0;i<n;i++)
cin>>a[i];

for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[j]<a[i])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
pass++;
}
for(i=0;i<n;++i)
for(j=i+1;j<n;)
{
if(a[i]==a[j])
{
for(k=j;k<n-1;++k)
a[k]=a[k+1];

--n;
}
else
++j;
}

cout<<"\n";
for(i=0;i<n;i++)
cout<<a[i]<<" ";

return 0;
}```

I hope, you have understood how our program works to sort an array and remove the duplicate elements in it in C++ language.