Just use sort to sort the final output. But arrays are of type short int. Otherwise, it will exceed memory.
#include<bits/stdc++.h> using namespace std; int n,m;short int a[1000010]; int main(){ scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) scanf("%d",&a[i]); sort(a+1,a+n+1); for(int i=1;i<=m;i++) printf("%d\n",a[i]); return 0; }