Given an array of n elements and an integer k. Group the elements in k. And then sort the array.n will always be multiple of k. Ex: [1, 23, 4, 3, 8, 9] and k = 2. So number formed are 123, 43, 89. Now after sorting, it will be 43, 89, 123. Return the array as [4,3,8,9,1,23].
#include <bits/stdc++.h>
using namespace std;
bool cmp (pair <string, int> a, pair <string, int> b) {
string c= a.first, d= b.first;
if (c.length() < d.length())
return 1;
else if (c.length() > d.length())
return 0;
else
return c<d;
}
int main() {
int n, k;
cin>>n>>k;
vector <int> a(n);
for (int i=0;i<n;i++)
cin>> a[i];
vector < pair <string, int> > v;//to store the grouped elements and starting index of group.
int i=0;
while (i<n) {// join the numbers in groups of k elements.
int count= 0;
string temp= "";
while (count<k && i<n) {
temp+= to_string(a[i]);
i++;
count++;
}
v.push_back(make_pair(temp, i-k));
}
sort (v.begin(), v.end(), cmp);//sort the newly formed numbers
vector <int> b(n);
i=0;
int j=0;
while (i<v.size()) {
int t= v[i].second, count= 0;
while (t<n && count<k) {
b[j]= a[t];
t++;
j++;
count++;
}
i++;
}
for(int i=0;i<n;i++)
cout<<b[i]<<" ";
}