Sort given Array using at most N cyclic shift on any subarray
Last Updated :
21 Dec, 2021
Given an array arr[] containing N integers, with duplicates. The task is to sort the array in increasing order using at most N cyclic shift on any sub-array.
Cyclic shift on any sub-array means cut out any subarray from the given array, use cyclic shift (rotate) in it by any offset, and put it back into the same place of the array.
Print the number of such shifting required to sort the array. There can be multiple possibilities.
Examples:
Input: arr[] = [1, 3, 2, 8, 5]
Output: 2
Explanation: Consider segment from index = 1 to index = 2. [1, 3, 2, 8, 5]. Now rotate this segment by 1 offset. The new array becomes, [1, 2, 3, 8, 5].
Then consider segment from index = 3 to index = 4, [1, 2, 3, 8, 5]. Rotate it by 1 offset, the new array becomes, [1, 2, 3, 5, 8].
Input: arr[] = [2, 4, 1, 3]
Output: 2
Explanation: From index = 0 to index = 2, [2, 4, 1, 3]. Rotate this segment by 2 offset on left, the new array becomes, [1, 2, 4, 3].
Taking second segment from index = 2 to index = 3 of offset 1, rotate it the new array becomes, [1, 2, 4, 3].
Approach: There can be two cases:
- Case when the array is already sorted: Then we do not need to perform any shifting operation
- Case when the array is not sorted: For that follow the steps mentioned below:
- Create a variable count = 0 to store the total number of counts.
- Iterate from i = 0 to i = N-2. And for each iteration do the following operations:
- Create a variable minVal to store the minimum value found in this iteration and initiate it with the value of arr[i].
- Start iterating from i+1 to N-1. If the current value is less than minVal, update minVal.
- Mark that position right to perform cyclic shift from i to right by offset 1.
- If no such right value exists then simply move to the next iteration.
- Otherwise, rotate the array from i to right by 1 position and increment count by 1.
- Return the value of count as your answer.
Below is the C++ implementation for the above approach:
C++
// C++ code to implement the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to Sort given Array using
// at most N cyclic shift on any subarray
int ShiftingSort(vector<int>& arr, int n)
{
vector<int> temp(arr.begin(), arr.end());
sort(temp.begin(), temp.end());
// Variable to store count of
// shifting operations
int count = 0;
// If the vector arr is already sorted
// the 0 operations shift required
if (arr == temp) {
return 0;
}
else {
// Run a loop from 0 to n-2 index
for (int index1 = 0; index1 < n - 1; index1++) {
int minval = arr[index1];
int left = index1;
int right = -1;
// Loop from i+1 to n-1
// to find the minimum value
for (int index2 = index1 + 1; index2 < n;
index2++) {
if (minval > arr[index2]) {
minval = arr[index2];
right = index2;
}
}
// Check if the shifting is required
if (right != -1) {
// Increment count operations
count++;
int index = right;
int tempval = arr[right];
// Loop for shifting the array arr
// from index = left to index = right
while (index > left) {
arr[index] = arr[index - 1];
index--;
}
arr[index] = tempval;
}
}
}
// Return the total operations
return count;
}
// Driver code
int main()
{
vector<int> arr{ 1, 3, 2, 8, 5 };
int N = 5;
cout << ShiftingSort(arr, N) << "\n";
return 0;
}
Java
// Java code to implement the above approach
import java.util.*;
public class GFG
{
// Function to Sort given Array using
// at most N cyclic shift on any subarray
static int ShiftingSort(ArrayList<Integer> arr, int n)
{
ArrayList<Integer> temp = new ArrayList<Integer>();
for(int i = 0; i < arr.size(); i++) {
temp.add(arr.get(i));
}
Collections.sort(temp);
// Variable to store count of
// shifting operations
int count = 0;
// If the vector arr is already sorted
// the 0 operations shift required
if (arr.equals(temp)) {
return 0;
}
else {
// Run a loop from 0 to n-2 index
for (int index1 = 0; index1 < n - 1; index1++) {
int minval = arr.get(index1);
int left = index1;
int right = -1;
// Loop from i+1 to n-1
// to find the minimum value
for (int index2 = index1 + 1; index2 < n;
index2++) {
if (minval > arr.get(index2)) {
minval = arr.get(index2);
right = index2;
}
}
// Check if the shifting is required
if (right != -1) {
// Increment count operations
count++;
int index = right;
int tempval = arr.get(right);
// Loop for shifting the array arr
// from index = left to index = right
while (index > left) {
arr.set(index, arr.get(index - 1));
index--;
}
arr.set(index, tempval);
}
}
}
// Return the total operations
return count;
}
// Driver code
public static void main(String args[])
{
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(1);
arr.add(3);
arr.add(2);
arr.add(8);
arr.add(5);
int N = 5;
System.out.println(ShiftingSort(arr, N));
}
}
// This code is contributed by Samim Hossain Mondal.
Python3
# Python Program to implement
# the above approach
# Function to Sort given Array using
# at most N cyclic shift on any subarray
def ShiftingSort(arr, n):
temp = arr.copy()
temp.sort()
# Variable to store count of
# shifting operations
count = 0
# If the vector arr is already sorted
# the 0 operations shift required
if (arr == temp):
return 0
else:
# Run a loop from 0 to n-2 index
for index1 in range(n - 1):
minval = arr[index1]
left = index1
right = -1
# Loop from i+1 to n-1
# to find the minimum value
for index2 in range(index1 + 1, n):
if (minval > arr[index2]):
minval = arr[index2]
right = index2
# Check if the shifting is required
if (right != -1):
# Increment count operations
count += 1
index = right
tempval = arr[right]
# Loop for shifting the array arr
# from index = left to index = right
while (index > left):
arr[index] = arr[index - 1]
index -= 1
arr[index] = tempval
# Return the total operations
return count
# Driver code
arr = [1, 3, 2, 8, 5]
N = 5
print(ShiftingSort(arr, N))
# This code is contributed by gfgking
C#
// C# code to implement the above approach
using System;
using System.Collections;
using System.Collections.Generic;
class GFG
{
// Function to Sort given Array using
// at most N cyclic shift on any subarray
static int ShiftingSort(ArrayList arr, int n)
{
ArrayList temp = new ArrayList();
for(int i = 0; i < arr.Count; i++) {
temp.Add(arr[i]);
}
temp.Sort();
// Variable to store count of
// shifting operations
int count = 0;
// If the vector arr is already sorted
// the 0 operations shift required
if (arr.Equals(temp)) {
return 0;
}
else
{
// Run a loop from 0 to n-2 index
for (int index1 = 0; index1 < n - 1; index1++) {
int minval = (int)arr[index1];
int left = index1;
int right = -1;
// Loop from i+1 to n-1
// to find the minimum value
for (int index2 = index1 + 1; index2 < n;
index2++) {
if (minval > (int)arr[index2]) {
minval = (int)arr[index2];
right = index2;
}
}
// Check if the shifting is required
if (right != -1)
{
// Increment count operations
count++;
int index = right;
int tempval = (int)arr[right];
// Loop for shifting the array arr
// from index = left to index = right
while (index > left) {
arr[index] = arr[index - 1];
index--;
}
arr[index] = tempval;
}
}
}
// Return the total operations
return count;
}
// Driver code
public static void Main()
{
ArrayList arr = new ArrayList();
arr.Add(1);
arr.Add(3);
arr.Add(2);
arr.Add(8);
arr.Add(5);
int N = 5;
Console.Write(ShiftingSort(arr, N));
}
}
// This code is contributed by Samim Hossain Mondal.
JavaScript
<script>
// JavaScript Program to implement
// the above approach
// Function to Sort given Array using
// at most N cyclic shift on any subarray
function ShiftingSort(arr, n) {
let temp = [...arr];
temp.sort(function (a, b) { return a - b })
// Variable to store count of
// shifting operations
let count = 0;
// If the vector arr is already sorted
// the 0 operations shift required
if (arr == temp) {
return 0;
}
else {
// Run a loop from 0 to n-2 index
for (let index1 = 0; index1 < n - 1; index1++) {
let minval = arr[index1];
let left = index1;
let right = -1;
// Loop from i+1 to n-1
// to find the minimum value
for (let index2 = index1 + 1; index2 < n;
index2++) {
if (minval > arr[index2]) {
minval = arr[index2];
right = index2;
}
}
// Check if the shifting is required
if (right != -1)
{
// Increment count operations
count++;
let index = right;
let tempval = arr[right];
// Loop for shifting the array arr
// from index = left to index = right
while (index > left) {
arr[index] = arr[index - 1];
index--;
}
arr[index] = tempval;
}
}
}
// Return the total operations
return count;
}
// Driver code
let arr = [1, 3, 2, 8, 5];
let N = 5;
document.write(ShiftingSort(arr, N) + '<br>');
// This code is contributed by Potta Lokesh
</script>
Time Complexity: O(N2)
Space Complexity: O(1)
Similar Reads
Check if a decreasing Array can be sorted using Triple cyclic shift Given an arr[] of size N whose elements are sorted in descending order. The task is to find if the given array can be sorted in ascending order by performing a minimum number of triple cyclic right swaps. Print the indexes involved in each of the triple cyclic right swap. Triple Cyclic Right Swap re
8 min read
Sorting possible using size 3 subarray rotation Given an array of integer values which need to be sorted by only one operation â subarray rotation where subarray size should be 3. For example, If our array is (1 2 3 4) then we can reach to (1 4 2 3), (3 1 2 4) in one step. We need to tell whether it is possible to sort the complete array with thi
12 min read
Count swaps required to sort an array using Insertion Sort Given an array A[] of size N (1 ⤠N ⤠105), the task is to calculate the number of swaps required to sort the array using insertion sort algorithm.Examples:Input: A[] = {2, 1, 3, 1, 2} Output: 4 Explanation:Step 1: arr[0] stays in its initial position. Step 2: arr[1] shifts 1 place to the left. Coun
15 min read
Sort an array by left shifting digits of array elements Given an array arr[] consisting of N positive integers, the task is to left-shift the digits of array elements such that the array modifies to a sorted form. If multiple solutions exist, then print any one of them. Otherwise, print -1. Examples: Input: arr[] = { 511, 321, 323, 432 } Output: { 115, 1
8 min read
Sort a string lexicographically using triple cyclic shifts Given a string consisting of the first N distinct alphabets, the task is to sort the string by using at most N/2 moves. Each move involves the following: Select any 3 distinct indices.Perform a cyclic shift on the alphabets at these indices. If it is possible to sort the strings, print the count of
11 min read
Check if Array can be sorted in non-decreasing order using given operations Given an array arr[] of size N consisting of positive integers, the task is to check if the array can be sorted in non-decreasing order by performing the following operations: Select two adjacent elements.Swap the elements and invert their signs.All elements in the sorted array received at the end,
8 min read