Nearly Sorted Algorithm | Practice | GeeksforGeeks

Given an array of n elements, where each element is at most k away from its target position. The task is to print array in sorted form.
Input:
First line consists of T test cases. First line of every test case consists of two integers N and K, denoting number of elements in array and at most k positions away from its target position respectively. Second line of every test case consists of elements of array.
Output:
Single line output to print the sorted array.
Constraints:
1<=T<=100
1<=N<=100
1<=K
Example:
Input:
2
3 3
2 1 3
6 3
2 6 3 12 56 8
Output:
1 2 3
2 3 6 8 12 56
0
abytespaceneeded2 weeks ago
#include<iostream>
#include<vector>
#include<queue>
using namespace std;

void sortK(vector<int> &arr, int k)
{
    priority_queue<int,vector<int>,greater<int>> pq;
    
    if(arr.size() == k)
        k = k-1;
    
    for(int i=0;i<=k;i++)
        pq.push(arr[i]);
        
    int index = 0;
    
    for(int i=k+1;i<arr.size();i++)
    {
        arr[index] = pq.top();
        pq.pop();
        pq.push(arr[i]);
        ++index;
    }
    
    while(pq.empty() == false)
    {
        arr[index] = pq.top();
        pq.pop();
        ++index;
    }
}

int main()
 {
	//code
	int T;
	cin>>T;
	
	while(T--) {
	int N,K;
	cin>>N>>K;
	
	vector<int> arr(N,0);
	for(int i=0;i<N;i++)
	    cin>>arr[i];
	   
    sortK(arr,K);
    
    for(int i=0;i<N;i++)
        cout<<arr[i]<<" ";
    
    cout<<endl;
	}
    
	return 0;
}
0
rockzthakur1998091 month ago
 
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
while(t--)
{
    int n,k;
    cin>>n>>k;
    int arr[n];
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
     priority_queue<int,vector<int>,greater<int>>pq;
     for(int i=0;i<k;i++)
    {
      pq.push(arr[i]);
    }
    for(int i=k;i<n;i++)
    {
     cout<<pq.top()<<" ";
     pq.pop();
     pq.push(arr[i]);
    }
      while(!pq.empty())
     {
      cout<<pq.top()<<" ";
      pq.pop();
     }
      cout<<endl;
    
   }
return 0;
}
+1
aloksinghbais022 months ago
C++ solution using priority_queue having time complexity as O(min(n,k)*log(min(n,k))) and space complexity as O(min(n,k)) is as follows :- 
 
Execution Time :- 0.0 / 1.6 sec
 
#include <bits/stdc++.h>#define ll long long int#define ld long double#define FIO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);#define mod ((int)1e9+7)#define inf 1e18#define hell 1e15#define p_b push_backusing namespace std;
 
void nearlySortedAlgo(int arr[],int n,int k){ 
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq;   for(int i = 0; i < min(k,n); i++){       pq.push({arr[i],i});   }      int i = 0;   while(i+k < n && !pq.empty()){       arr[i] = pq.top().first;       pq.pop();       pq.push({arr[i+k],i+k});       i++;   }      while(i < n){       arr[i++] = pq.top().first;       pq.pop();   }}
 
int main(int args,char **ch){   FIO   int t; cin>>t;   while(t--){       int n,k; cin>>n>>k;       int arr[n]; for(int i=0; i<n; i++) cin>>arr[i];       nearlySortedAlgo(arr,n,k);       for(int i=0; i<n; i++) cout<<arr[i]<<" ";       cout<<endl;   }      return (0);}
+1
abhixhek052 months ago
 vector <int> nearlySorted(int arr[], int num, int k){
        // Your code here
        priority_queue<int,vector<int>,greater<int>>q;
        for(int i=0;i<=k;i++){
            q.push(arr[i]);
        }
        vector<int>ans;
         for(int i = k + 1; i<num; ++i)
	    {
	         ans.push_back(q.top ());
	        q.pop();
	        q.push(arr[i]);
	        
	    }
        
        while(q.size()){
            int a = q.top();
            q.pop();
            ans.push_back(a);
        }
        
        return ans;
    }
0
rathoredivya1502 months ago
in this complexity reduced so the use of k can be seen.
 
#include <bits/stdc++.h>using namespace std;
int main() {   int t;   cin>>t;
   priority_queue<int,vector<int>,greater<int>>pq;   vector<int>v;   while(t--){       v.clear();          int n,k;       cin>>n>>k;       int arr[n];       for(int i=0;i<n;i++)       {           cin>>arr[i];       }   for(int i=0;i<n;i++)   {        pq.push(arr[i]);
   if(pq.size()>k)   {      v.push_back(pq.top());       pq.pop();   }   }   while(pq.size()>0)   {       v.push_back(pq.top());       pq.pop();   }
for(auto a:v){   cout<<a<<" ";}cout<<"\n";   }//codereturn 0;} 
0
aniketsaraswat1122 months ago
#include <bits/stdc++.h>
using namespace std;

int main() {
	int t; cin>>t;
	while(t--){
	    int n,k; cin>>n>>k;
	    int arr[n];
	    priority_queue<int,vector<int>,greater<int>> pq;
	    for(int i = 0; i<n; i++) cin>>arr[i];
	    for(int i = 0; i<k; i++) pq.push(arr[i]);
	    int i;
	    for(i = 0; i<n-k; i++) arr[i] = pq.top(),
	    pq.pop(),pq.push(arr[i+k]);
	    while(!pq.empty()) arr[i++] = pq.top(),pq.pop();
	    for(auto i : arr) cout<<i<<" ";
	    cout<<endl;
	}
	return 0;
}
0
raidivyansh252 months ago
#include <iostream>#include<queue>using namespace std;
int main() {int t;cin>>t;while(t--){ int n,k;    cin>>n>>k;    int arr[n];    for(int &x:arr)    cin>>x;        priority_queue<int, vector<int>,greater<int>>pq(arr,arr+k);    for(int i=k;i<n;i++)    {cout<<pq.top()<<" "; pq.pop();        pq.push(arr[i]);    }    while(!pq.empty())    {cout<<pq.top()<<" "; pq.pop();}    cout<<endl;}return 0;}
 
0
utkarshagarwal101
This comment was deleted.
0
joshichinmay2813 months ago
C++ Simple solution by using Functions(Beginner Friendly)
100/100 Test Cases Passed...
 
#include <iostream>using namespace std;void sorty(int arr[], int n){   for(int i=0 ; i<n ; i++)   {       for(int j=i ; j<n ; j++)       {           if(arr[i] > arr[j])           {               int temp = arr[i];               arr[i] = arr[j];               arr[j] = temp;           }       }   }}
void printArray(int arr[], int n){   for(int i=0 ; i<n ; i++)   {       cout << arr[i] <<" ";   }   cout << endl;}
int main() {int t;cin>>t;while(t--){    int n,k;    cin>>n>>k;    int arr[n];    for(int i=0 ; i<n ; i++)    {        cin>>arr[i];    }    sorty(arr,n);    printArray(arr,n);}return 0;}
+1
mdaman9993 months ago
Unusualperson c++ code:
 
#include<bits/stdc++.h>
using namespace std;
int main()
{
//code
int t; cin>>t;
while(t--){
    int n,k; cin>>n>>k;
    int arr[n];
    for(int i=0;i<n;i++) cin>>arr[i];
    sort(arr,arr+n);
    for(int i=0;i<n;i++) cout<<arr[i]<<" ";
    cout<<endl;
}
return 0;
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.