Tuesday, December 5, 2017

Sort In Subsets of Size K

Given N numbers, the program must sort within subsets of size K. That is every K numbers must be sorted among themselves. (The last subset may not have K numbers in certain cases, but the program must sort them too)

Input Format:
The first line contains N and K separated by space. The second line contains N numbers separated by space.

Output Format:
The first line contains N numbers sorted in subsets of size K.

Boundary Conditions: 2 <= N <= 9999
Value of a given number is from -99999 to 99999

Example Input/Output 1:
Input:
11
3 880 111 1440 1326 1892 -365 -761 -489 -131 1199 324
Output:
111 880 1440 -365 1326 1892 -761 -489 -131 324 1199

Solution:
#include <bits/stdc++.h>
using namespace std;
int main()
{
 int a,n,k,i;
 cin>>n>>k;
 vector<int> v;
 while(cin>>a)
  v.push_back(a);
 for(i=0;i+k<=n;i+=k)
 sort(v.begin()+i,v.begin()+i+k);
 if(n%k!=0)
 sort(v.begin()+i,v.end());
 for(i=0;i<n;i++)
  cout<<v[i]<<" ";
}
Share: