Program to Cyclically Rotate an Array by k Positions

Cyclically Rotate an Array by K

Here, in this page we will discuss the program for cyclically rotate an array by k positions. We are given with an integer array and value of k, and need to print the array after cyclically rotate it by k positions.
Cyclically Rotate an Array by K

Method Discussed :

  • Method 1 : Using Temporary Array.
  • Method 2 : By rotating elements one by one.
  • Method 3 : By Using the reversing Concept.
  • Method 3 : Using juggling algorithm

Let’s discuss all the above methods one by one in brief,

Method 1 :

In this method we will declare an extra array to store some k elements. Here, k refers to number of rotations.

  • Declare a temporary array of size k.
  • Store the first k elements in temp[] array.
  • Now, shift the remaining elements.
  • After, shifting the elements add the elements of temp[] in the array

Output

50 60 70 10 20 30 40

Method 2 :

In this method we cyclically rotate the array by shifting elements one by one.

Output

50 60 70 10 20 30 40

Method 3 :

  • Set K to points that element which comes at first position, i.e. K = N-K.
  • Reverse the array from 0 to K-1 position.
  • Again reverse the array from K to N-1 position.
  • And then finally reverse the entire array.
  • Doing so we will get the desired circularly rotated array by K position.

Output

50 60 70 10 20 30 40

Method 4 :

In this method we will use the concept of juggling algorithm for cyclically rotate the array by K positions.

You can check out the page for understanding it’s algorithm.

Output

50 60 70 10 20 30 40

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription

One comment on “Program to Cyclically Rotate an Array by k Positions”


  • Gyanendra

    import java.util.*;
    public class Main
    {
    public static void main (String[]args)
    {

    int[] arr= {10, 20, 30, 40, 50, 60, 70};

    int k=4-1;

    reverse(arr,0,arr.length-k-1);
    reverse(arr,arr.length-k,arr.length-1);
    reverse(arr,0,arr.length-1);

    for(int val:arr){
    System.out.print(val+” “);
    }
    }

    public static void reverse(int[] arr,int i,int j){

    while(i<j){
    int temp=arr[i];
    arr[i]=arr[j];
    arr[j]=temp;
    i++;
    j–;
    }
    }
    }