Thursday, December 26, 2024
Google search engine
HomeData Modelling & AIBlock swap algorithm for array rotation

Block swap algorithm for array rotation

Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements. 

Array

Rotation of the above array by 2 will make an array

ArrayRotation1

Algorithm : 

Initialize A = arr[0..d-1] and B = arr[d..n-1]
1) Do following until size of A is equal to size of B

  a)  If A is shorter, divide B into Bl and Br such that Br is of same 
       length as A. Swap A and Br to change ABlBr into BrBlA. Now A
       is at its final place, so recur on pieces of B.  

   b)  If A is longer, divide A into Al and Ar such that Al is of same 
       length as B Swap Al and B to change AlArB into BArAl. Now B
       is at its final place, so recur on pieces of A.





2)  Finally when A and B are of equal size, block swap them.

Recursive Implementation:

C++




#include <bits/stdc++.h>
using namespace std;
  
#include <bits/stdc++.h>
using namespace std;
  
/*UTILITY FUNCTIONS*/
/* function to print an array */
void printArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        cout << arr[i] << " ";
    cout << endl;
}
  
/*This function swaps d elements starting at index fi
with d elements starting at index si */
void swap(int arr[], int fi, int si, int d)
{
    int i, temp;
    for (i = 0; i < d; i++) {
        temp = arr[fi + i];
        arr[fi + i] = arr[si + i];
        arr[si + i] = temp;
    }
}
  
void leftRotate(int arr[], int d, int n)
{
    /* Return If number of elements to be rotated
    is zero or equal to array size */
    if (d == 0 || d == n)
        return;
    /* If number of elements to be rotated is more than
     * array size*/
    if (d > n)
        d = d % n;
    /*If number of elements to be rotated
    is exactly half of array size */
    if (n - d == d) {
        swap(arr, 0, n - d, d);
        return;
    }
  
    /* If A is shorter*/
    if (d < n - d) {
        swap(arr, 0, n - d, d);
        leftRotate(arr, d, n - d);
    }
    else /* If B is shorter*/
    {
        swap(arr, 0, d, n - d);
        leftRotate(arr + n - d, 2 * d - n,
                   d); /*This is tricky*/
    }
}
  
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
    leftRotate(arr, 2, 7);
    printArray(arr, 7);
    return 0;
}
  
// This code is contributed by rathbhupendra


C




#include<stdio.h>
  
/*Prototype for utility functions */
void printArray(int arr[], int size);
void swap(int arr[], int fi, int si, int d);
  
void leftRotate(int arr[], int d, int n)
  /* Return If number of elements to be rotated is 
    zero or equal to array size */  
  if(d == 0 || d == n)
    return;
      
  /*If number of elements to be rotated is exactly 
    half of array size */  
  if(n-d == d)
  {
    swap(arr, 0, n-d, d);   
    return;
  }  
      
 /* If A is shorter*/              
  if(d < n-d)
  {  
    swap(arr, 0, n-d, d);
    leftRotate(arr, d, n-d);    
  }    
  else /* If B is shorter*/              
  {
    swap(arr, 0, d, n-d);
    leftRotate(arr+n-d, 2*d-n, d); /*This is tricky*/
  }
}
  
/*UTILITY FUNCTIONS*/
/* function to print an array */
void printArray(int arr[], int size)
{
  int i;
  for(i = 0; i < size; i++)
    printf("%d ", arr[i]);
  printf("\n ");
  
/*This function swaps d elements starting at index fi
  with d elements starting at index si */
void swap(int arr[], int fi, int si, int d)
{
   int i, temp;
   for(i = 0; i<d; i++)   
   {
     temp = arr[fi + i];
     arr[fi + i] = arr[si + i];
     arr[si + i] = temp;
   }     
}     
  
/* Driver program to test above functions */
int main()
{
   int arr[] = {1, 2, 3, 4, 5, 6, 7};
   leftRotate(arr, 2, 7);
   printArray(arr, 7);
   getchar();
   return 0;
}    


Java




import java.util.*;
  
class GFG 
{
    // Wrapper over the recursive function leftRotateRec()
    // It left rotates arr[] by d.
    public static void leftRotate(int arr[], int d, 
                                                int n)
    {
        leftRotateRec(arr, 0, d, n);
    }
  
    public static void leftRotateRec(int arr[], int i, 
                                  int d, int n)
    {
        /* Return If number of elements to be rotated 
        is zero or equal to array size */
        if(d == 0 || d == n) 
            return
          
        /*If number of elements to be rotated 
        is exactly half of array size */
        if(n - d == d) 
        
            swap(arr, i, n - d + i, d); 
            return
        
          
        /* If A is shorter*/    
        if(d < n - d) 
        
            swap(arr, i, n - d + i, d); 
            leftRotateRec(arr, i, d, n - d);     
        
        else /* If B is shorter*/    
        
            swap(arr, i, d, n - d); 
            leftRotateRec(arr, n - d + i, 2 * d - n, d); /*This is tricky*/
        
    }
  
/*UTILITY FUNCTIONS*/
/* function to print an array */
public static void printArray(int arr[], int size) 
    int i; 
    for(i = 0; i < size; i++) 
        System.out.print(arr[i] + " "); 
    System.out.println(); 
  
/*This function swaps d elements 
starting at index fi with d elements
starting at index si */
public static void swap(int arr[], int fi,
                        int si, int d) 
    int i, temp; 
    for(i = 0; i < d; i++) 
    
        temp = arr[fi + i]; 
        arr[fi + i] = arr[si + i]; 
        arr[si + i] = temp; 
    
  
// Driver Code
public static void main (String[] args) 
{
    int arr[] = {1, 2, 3, 4, 5, 6, 7}; 
    leftRotate(arr, 2, 7); 
    printArray(arr, 7);     
}
}
  
// This code is contributed by codeseeker


Python3




# Wrapper over the recursive function leftRotateRec()
# It left rotates arr by d.
def leftRotate(arr, d, n):
    leftRotateRec(arr, 0, d, n);
  
def leftRotateRec(arr, i, d, n):
    '''
     * Return If number of elements to be 
     rotated is zero or equal to array size
     '''
    if (d == 0 or d == n):
        return;
  
    '''
     * If number of elements to be rotated 
     is exactly half of array size
     '''
    if (n - d == d):
        swap(arr, i, n - d + i, d);
        return;
  
    ''' If A is shorter '''
    if (d < n - d):
        swap(arr, i, n - d + i, d);
        leftRotateRec(arr, i, d, n - d);
        ''' If B is shorter '''
    else:
        swap(arr, i, d, n - d);
          
        ''' This is tricky '''
        leftRotateRec(arr, n - d + i, 2 * d - n, d); 
  
''' UTILITY FUNCTIONS '''
''' function to print an array '''
def printArray(arr, size):
    for i in range(size):
        print(arr[i], end = " ");
    print();
  
'''
 * This function swaps d elements starting at 
 * index fi with d elements starting at index si
 '''
def swap(arr, fi, si, d):
    for i in range(d):
        temp = arr[fi + i];
        arr[fi + i] = arr[si + i];
        arr[si + i] = temp;
  
# Driver Code
if __name__ == '__main__':
    arr = [1, 2, 3, 4, 5, 6, 7];
    leftRotate(arr, 2, 7);
    printArray(arr, 7);
  
# This code is contributed by Rohit_ranjan


C#




using System;
  
class GFG{
      
// Wrapper over the recursive function
// leftRotateRec() 
// It left rotates []arr by d.
public static void leftRotate(int []arr, 
                              int d, int n)
{
    leftRotateRec(arr, 0, d, n);
}
  
public static void leftRotateRec(int []arr, int i, 
                                 int d, int n)
{
      
    // Return If number of elements 
    // to be rotated is zero or equal
    // to array size
    if(d == 0 || d == n) 
        return
      
    // If number of elements to be rotated 
    // is exactly half of array size 
    if(n - d == d) 
    
        swap(arr, i, n - d + i, d); 
        return
    
      
    // If A is shorter
    if(d < n - d) 
    
        swap(arr, i, n - d + i, d); 
        leftRotateRec(arr, i, d, n - d);     
    
      
    // If B is shorter
    else 
    
        swap(arr, i, d, n - d); 
          
        // This is tricky
        leftRotateRec(arr, n - d + i, 
                       2 * d - n, d); 
    
}
  
// UTILITY FUNCTIONS
// Function to print an array 
public static void printArray(int []arr,
                              int size) 
    int i; 
    for(i = 0; i < size; i++) 
        Console.Write(arr[i] + " "); 
          
    Console.WriteLine(); 
  
// This function swaps d elements 
// starting at index fi with d elements
// starting at index si 
public static void swap(int []arr, int fi,
                        int si, int d) 
    int i, temp; 
    for(i = 0; i < d; i++) 
    
        temp = arr[fi + i]; 
        arr[fi + i] = arr[si + i]; 
        arr[si + i] = temp; 
    
  
// Driver Code
public static void Main(String[] args) 
{
    int []arr = { 1, 2, 3, 4, 5, 6, 7 }; 
      
    leftRotate(arr, 2, 7); 
    printArray(arr, 7);     
}
}
  
// This code is contributed by amal kumar choubey


Javascript




<script>
  
let leftRotate = (arr, d, n) =>{ 
    /* Return If number of elements to be rotated  
    is zero or equal to array size */
    if(d == 0 || d == n) 
        return
          
    /*If number of elements to be rotated 
    is exactly half of array size */
    if(n - d == d) { 
        arr = swap(arr, 0, n - d, d); 
        return
    
          
    /* If A is shorter*/        
    if(d < n - d) { 
        arr = swap(arr, 0, n - d, d); 
        leftRotate(arr, d, n - d);     
    
    else{             
    /* If B is shorter*/  
        arr = swap(arr, 0, d, n - d); 
        /*This is tricky*/
        leftRotate(arr + n - d, 2 * d - n, d); 
    
  
/*UTILITY FUNCTIONS*/
/* function to print an array */
let printArray = (arr, size) =>{ 
    ans = ''
    for(let i = 0; i < size; i++) 
        ans += arr[i]+" ";
    document.write(ans)
  
/*This function swaps d elements 
starting at index fi 
with d elements starting at index si */
let swap = (arr, fi, si, d) =>{  
    for(let i = 0; i < d; i++) { 
        let temp = arr[fi + i]; 
        arr[fi + i] = arr[si + i]; 
        arr[si + i] = temp; 
    
    return arr
  
// Driver Code
arr = [1, 2, 3, 4, 5, 6, 7]; 
leftRotate(arr, 2, 7); 
printArray(arr, 7); 
  
</script>


Output

3 4 5 6 7 1 2 

Time Complexity: O(n)
Auxiliary Space: O(log n)

Iterative Implementation: 
Here is an iterative implementation of the same algorithm. The same utility function swap() is used here.

C++




// C++ code for above implementation
#include <bits/stdc++.h>
using namespace std;
  
/*UTILITY FUNCTIONS*/
/* function to print an array */
void printArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        cout << arr[i] << " ";
    cout << endl;
}
  
/*This function swaps d elements starting at index fi
with d elements starting at index si */
void swap(int arr[], int fi, int si, int d)
{
    int i, temp;
    for (i = 0; i < d; i++) {
        temp = arr[fi + i];
        arr[fi + i] = arr[si + i];
        arr[si + i] = temp;
    }
}
  
// This code is contributed by rathbhupendra
  
void leftRotate(int arr[], int d, int n)
{
    int i, j;
    if (d == 0 || d == n)
        return;
  
    /* If number of elements to be rotated is more than
     * array size*/
    if (d > n)
        d = d % n;
  
    i = d;
    j = n - d;
    while (i != j) {
        if (i < j) /*A is shorter*/
        {
            swap(arr, d - i, d + j - i, i);
            j -= i;
        }
        else /*B is shorter*/
        {
            swap(arr, d - i, d, j);
            i -= j;
        }
  
        // printArray(arr, 7);
    }
  
    /*Finally, block swap A and B*/
    swap(arr, d - i, d, i);
}
  
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
    leftRotate(arr, 2, 7);
    printArray(arr, 7);
    return 0;
}
  
// This code is contributed by Shivani


C




// C code for above implementation
  
#include <stdio.h>
  
/*UTILITY FUNCTIONS*/
/* function to print an array */
void printArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        printf("%d ", arr[i]);
    printf("\n ");
}
  
/*This function swaps d elements starting at index fi
  with d elements starting at index si */
void swap(int arr[], int fi, int si, int d)
{
    int i, temp;
    for (i = 0; i < d; i++) {
        temp = arr[fi + i];
        arr[fi + i] = arr[si + i];
        arr[si + i] = temp;
    }
}
  
void leftRotate(int arr[], int d, int n)
{
    int i, j;
    if (d == 0 || d == n)
        return;
    /* If number of elements to be rotated is more than
     * array size*/
    if (d > n)
        d = d % n;
    i = d;
    j = n - d;
    while (i != j) {
        if (i < j) /*A is shorter*/
        {
            swap(arr, d - i, d + j - i, i);
            j -= i;
        }
        else /*B is shorter*/
        {
            swap(arr, d - i, d, j);
            i -= j;
        }
        // printArray(arr, 7);
    }
    /*Finally, block swap A and B*/
    swap(arr, d - i, d, i);
}
  
/* Driver program to test above functions */
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
    leftRotate(arr, 2, 7);
    printArray(arr, 7);
    getchar();
    return 0;
}


Java




// Java code for above implementation
import java.io.*;
  
public class GFG {
    static void leftRotate(int arr[], int d, int n)
    {
        int i, j;
        if (d == 0 || d == n)
            return;
        /* If number of elements to be rotated is more than
         * array size*/
        if (d > n)
            d = d % n;
        i = d;
        j = n - d;
        while (i != j) {
            if (i < j) /*A is shorter*/
            {
                swap(arr, d - i, d + j - i, i);
                j -= i;
            }
            else /*B is shorter*/
            {
                swap(arr, d - i, d, j);
                i -= j;
            }
            // printArray(arr, 7);
        }
        /*Finally, block swap A and B*/
        swap(arr, d - i, d, i);
    }
  
    /*UTILITY FUNCTIONS*/
    /* function to print an array */
    public static void printArray(int arr[], int size)
    {
        int i;
        for (i = 0; i < size; i++)
            System.out.print(arr[i] + " ");
        System.out.println();
    }
  
    /*This function swaps d elements
    starting at index fi with d elements
    starting at index si */
    public static void swap(int arr[], int fi, int si,
                            int d)
    {
        int i, temp;
        for (i = 0; i < d; i++) {
            temp = arr[fi + i];
            arr[fi + i] = arr[si + i];
            arr[si + i] = temp;
        }
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
        leftRotate(arr, 2, 7);
        printArray(arr, 7);
    }
}


Python3




# Python3 code for above implementation
  
# Wrapper over the recursive function leftRotateRec()
# It left rotates arr by d.
  
  
''' UTILITY FUNCTIONS '''
''' function to print an array '''
  
  
def printArray(arr, size):
    for i in range(size):
        print(arr[i], end=" ")
    print()
  
  
'''
 * This function swaps d elements starting at 
 * index fi with d elements starting at index si
 '''
  
  
def swap(arr, fi, si, d):
    for i in range(d):
        temp = arr[fi + i]
        arr[fi + i] = arr[si + i]
        arr[si + i] = temp
  
  
def leftRotate(arr, d, n):
    if(d == 0 or d == n):
        return
    i = d
    j = n - d
    while (i != j):
  
        if(i < j):  # A is shorter
            swap(arr, d - i, d + j - i, i)
            j -= i
  
        else# B is shorter
            swap(arr, d - i, d, j)
            i -= j
  
    swap(arr, d - i, d, i)
  
  
    # Driver Code
if __name__ == '__main__':
    arr = [1, 2, 3, 4, 5, 6, 7]
    leftRotate(arr, 2, 7)
    printArray(arr, 7)


C#




// C# code for above implementation
  
using System;
  
class GFG {
  
    // UTILITY FUNCTIONS
    // Function to print an array
    public static void printArray(int[] arr, int size)
    {
        int i;
        for (i = 0; i < size; i++)
            Console.Write(arr[i] + " ");
  
        Console.WriteLine();
    }
  
    // This function swaps d elements
    // starting at index fi with d elements
    // starting at index si
    public static void swap(int[] arr, int fi, int si,
                            int d)
    {
        int i, temp;
        for (i = 0; i < d; i++) {
            temp = arr[fi + i];
            arr[fi + i] = arr[si + i];
            arr[si + i] = temp;
        }
    }
  
    static void leftRotate(int[] arr, int d, int n)
    {
        int i, j;
        if (d == 0 || d == n)
            return;
        /* If number of elements to be rotated is more than
         * array size*/
        if (d > n)
            d = d % n;
  
        i = d;
        j = n - d;
        while (i != j) {
            if (i < j) /*A is shorter*/
            {
                swap(arr, d - i, d + j - i, i);
                j -= i;
            }
            else /*B is shorter*/
            {
                swap(arr, d - i, d, j);
                i -= j;
            }
        }
  
        /*Finally, block swap A and B*/
        swap(arr, d - i, d, i);
    }
  
    // Driver Code
    public static void Main(String[] args)
    {
        int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
  
        leftRotate(arr, 2, 7);
        printArray(arr, 7);
    }
}
  
// This code is contributed by Rajput-Ji


Javascript




<script>
// JavaScript code for above implementation
function leftRotate(arr, d, n)
{
    if(d == 0 || d == n)
        return
    let i = d;
    let j = n - d;
    while (i != j)
    {
        if(i < j) 
        {
          
        // A is shorter
            arr = swap(arr, d - i, d + j - i, i);
            j -= i;
        }
        else{ // B is shorter
            arr = swap(arr, d - i, d, j);
            i -= j;
        }
    }
    arr = swap(arr, d - i, d, i);
      
    // This code is contributed by rohitsingh04052.
}
</script>


Output

3 4 5 6 7 1 2 

Time Complexity: O(n)
Auxiliary Space: O(1)

Please see the following posts for other methods of array rotation: 
https://www.geeksforgeeks.org/array-rotation/ 
https://www.geeksforgeeks.org/program-for-array-rotation-continued-reversal-algorithm/

Please write comments if you find any bug in the above programs/algorithms or want to share any additional information about the block swap algorithm.

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments