May be you can use this :
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;
int main()
{
int n=7;
int v[]={4,1,2,3,2,4,1}; // initial array
map<int,int>mp;
vector<int>uni;
for(int i=0;i<n;i++)
if(++mp[v[i]]==1) // counting instance of unique values
uni.push_back(v[i]); // unique value
sort(uni.begin(),uni.end()); // sorting : O ((n / logn) * logn) = O(n)
int cur=0;
for(int i=0;i<uni.size();i++)
{
int cnt=mp[uni[i]];
while(cnt) // Adding duplicate values
{
v[cur++]=uni[i];
cnt--;
}
}
for(int i=0;i<n;i++) // Printing final sorted array
cout<<v[i]<<" ";
cout<<"\n";
return 0;
}
Here uni
array keeps the unique values, that is maximum n / logn
values.
Then we used stl sort()
function having time complexity O (n * logn)
As here total element n = n / logn
. The complexity will be O ((n / logn) * logn) = O(n)
.
So we see that, above method works with O(n)
complexity with O(n * logn)
memory.
Here map<>
is used to count the number of times each distinct value appears.