Check if it is possible to sort an array with conditional swapping of elements at distance K

Given an array arr[] of n elements, we have to swap an index i with another index i + k any number of times and check whether it is possible to sort the given array arr[]. If it is then print “yes” otherwise print “no”.
Examples: 

Input: K = 2, arr = [4, 3, 2, 6, 7] 
Output: Yes 
Explanation: 
Choose index i = 0 and swap index i with i + k then the array becomes [2, 3, 4, 6, 7] which is sorted hence the output is “yes”. 
Input : K = 2, arr = [4, 2, 3, 7, 6] 
Output : No 
Explanation: 
It is not possible to obtain sorted array. 
 

Approach:
To solve the problem mentioned above we have to take the elements starting from index 0 and add the multiples of K to it, that is 0, 0 + k, 0 + (2*k), and so on. Swap these positions for all the indexes from 0 to K-1 and check if the final array is sorted. If it is, then return “yes” otherwise “no”.
Below is the implementation of the above approach:
 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP implementation to Check if it is possible to sort an
// array with conditional swapping of elements at distance K
#include <bits/stdc++.h>
using namespace std;
 
// Function for finding if it possible
// to obtain sorted array or not
bool fun(int arr[], int n, int k)
{
    vector<int> v;
 
    // Iterate over all elements until K
    for (int i = 0; i < k; i++) {
        // Store elements as multiples of K
        for (int j = i; j < n; j += k) {
            v.push_back(arr[j]);
        }
 
        // Sort the elements
        sort(v.begin(), v.end());
 
        int x = 0;
 
        // Put elements in their required position
        for (int j = i; j < n; j += k) {
            arr[j] = v[x];
            x++;
        }
 
        v.clear();
    }
 
    // Check if the array becomes sorted or not
    for (int i = 0; i < n - 1; i++) {
        if (arr[i] > arr[i + 1])
            return false;
    }
    return true;
}
 
// Driver code
int main()
{
    int arr[] = { 4, 2, 3, 7, 6 };
 
    int K = 2;
 
    int n = sizeof(arr) / sizeof(arr[0]);
 
    if (fun(arr, n, K))
        cout << "yes" << endl;
 
    else
        cout << "no" << endl;
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to check if it
// is possible to sort an array with
// conditional swapping of elements
// at distance K
import java.lang.*;
import java.io.*;
import java.util.*;
 
class GFG{
     
// Function for finding if it possible
// to obtain sorted array or not    
public static boolean fun(int[] arr, int n,
                                     int k)
{
    Vector<Integer> v = new Vector<Integer>();
 
    // Iterate over all elements until K
    for(int i = 0; i < k; i++)
    {
        
       // Store elements as multiples of K
       for(int j = i; j < n; j += k)
       {
          v.add(arr[j]);
       }
        
       // Sort the elements
       Collections.sort(v);
        
       int x = 0;
        
       // Put elements in their
       // required position
       for(int j = i; j < n; j += k)
       {
          arr[j] = v.get(x);
          x++;
       }
       v.clear();
    }
 
    // Check if the array becomes
    // sorted or not
    for(int i = 0; i < n - 1; i++)
    {
       if (arr[i] > arr[i + 1])
       {
           return false;
       }
    }
    return true;
}
 
// Driver code
public static void main (String args[])
{
    int[] arr = { 4, 2, 3, 7, 6 };
    int K = 2;
    int n = arr.length;
 
    if (fun(arr, n, K))
    {
        System.out.println("yes");
    }
    else
    {
        System.out.println("no");
    }
}
}
 
// This code is contributed by sayesha

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to Check if it is possible to sort an
# array with conditional swapping of elements at distance K
 
# Function for finding if it possible
# to obtain sorted array or not
def fun(arr, n, k):
 
    v = []
 
    # Iterate over all elements until K
    for i in range(k):
         
        # Store elements as multiples of K
        for j in range(i, n, k):
            v.append(arr[j]);
 
        # Sort the elements
        v.sort();
 
        x = 0
 
        # Put elements in their required position
        for j in range(i, n, k):
            arr[j] = v[x];
            x += 1
 
        v = []
 
    # Check if the array becomes sorted or not
    for i in range(n - 1):
        if (arr[i] > arr[i + 1]):
            return False
    return True
 
# Driver code
arr= [ 4, 2, 3, 7, 6 ]
 
K = 2;
 
n = len(arr)
 
if (fun(arr, n, K)):
    print("yes")
else:
    print("no")
     
# This code is contributed by apurva raj

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation to check if it
// is possible to sort an array with
// conditional swapping of elements
// at distance K
using System;
using System.Collections.Generic;
class GFG{
     
// Function for finding if it possible
// to obtain sorted array or not    
public static bool fun(int[] arr,
                       int n, int k)
{
    List<int> v = new List<int>();
 
    // Iterate over all elements until K
    for(int i = 0; i < k; i++)
    {      
       // Store elements as multiples of K
       for(int j = i; j < n; j += k)
       {
          v.Add(arr[j]);
       }
        
       // Sort the elements
       v.Sort();
        
       int x = 0;
        
       // Put elements in their
       // required position
       for(int j = i; j < n; j += k)
       {
          arr[j] = v[x];
          x++;
       }
       v.Clear();
    }
 
    // Check if the array becomes
    // sorted or not
    for(int i = 0; i < n - 1; i++)
    {
       if (arr[i] > arr[i + 1])
       {
           return false;
       }
    }
    return true;
}
 
// Driver code
public static void Main(String []args)
{
    int[] arr = {4, 2, 3, 7, 6};
    int K = 2;
    int n = arr.Length;
    if (fun(arr, n, K))
    {
        Console.WriteLine("yes");
    }
    else
    {
        Console.WriteLine("no");
    }
}
}
 
// This code is contributed by shikhasingrajput

chevron_right


Output: 

no



 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.