Cyclically rotate an array by k elements in C

Problem statement: Cyclically rotate an array by k elements  in C

Example:
input[] = {1, 2, 3, 4, 5, 6};
Key = 2
output[] = { 3, 4, 5, 6, 1, 2};

Store the last element in a temp variable.
Traverse and Shift all elements one by one by a position ahead.
Replace the first element of the array with the temp variable.
Do this for every iteration till k, k is the number of rotations.

//Cyclically rotate an array by k in C
#include <stdio.h>

void rotateByOne(int arr[], int n)
{
    int temp = arr[0], i;
    for (i = 0; i < n - 1; i++)
        arr[i] = arr[i + 1];
    arr[n - 1] = temp;
}

/*Function to left rotate arr[] of size n by d*/
void rotateByK(int arr[], int n, int k)
{
    int i;
    for (i = 0; i < k; i++)
        rotateByOne(arr, n);
}

void printArray(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        printf("%d\t", arr[i]);
}

int main()
{
    int n, key = 0;
    printf("Enter the number of element\t");
    scanf("%d", &n);
    int arr[n];
    printf("Enter array elements\n");
    for (int i = 0; i < n; i++)
        scanf("%d", &arr[i]);
    printf("Array elements are:\n");
    printArray(arr, n);
    printf("\nEnter the number to rotate from\t");
    scanf("%d", &key);
    rotateByK(arr, n, key);
    printf("\nArray elements after rotation:\n");
    printArray(arr, n);
    return 0;
}


 

$ gcc rotbyn.c
$ ./a.out
Enter the number of element 6
Enter array elements
1
2
3
4
5
6
Array elements are:
1 2 3 4 5 6
Enter the number to rotate from 2Array elements after rotation:
3 4 5 6 1 2 $
Time complexity: O(n*k)

also see

C Programming language
Go Programming language
Linked List Array
Simplification Queue
DBMS Reasoning
Aptitude HTML
Previous articleCyclically rotate an array by one in C
Next articleRearrange an array such that arr[i] = i in C

LEAVE A REPLY

Please enter your comment!
Please enter your name here