Array Rotation in C

This program demonstrates how to rotate an array by k positions using the C programming language. The rotation is performed in-place to optimize memory usage.

Explanation of the Program

The array rotation is performed by breaking the problem into three steps:

  1. Reverse the first part of the array (from index 0 to k-1).
  2. Reverse the second part of the array (from index k to n-1).
  3. Reverse the entire array (from index 0 to n-1).

By reversing these parts of the array, the elements are effectively rotated by k positions.

C Program

#include <stdio.h>

void reverse(int arr[], int start, int end) {
    int temp;
    while (start < end) {
        temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}

void rotateArray(int arr[], int n, int k) {
    // Handle cases where k is larger than n
    k = k % n;

    // Reverse the first part of the array
    reverse(arr, 0, k - 1);
    // Reverse the second part of the array
    reverse(arr, k, n - 1);
    // Reverse the entire array
    reverse(arr, 0, n - 1);
}

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

int main() {
    int arr[] = {1, 2, 3, 4, 5, 6, 7};
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;

    printf("Original array:\n");
    printArray(arr, n);

    rotateArray(arr, n, k);

    printf("Array after rotation by %d positions:\n", k);
    printArray(arr, n);

    return 0;
}

Program Output

Original array:
1 2 3 4 5 6 7 
Array after rotation by 3 positions:
4 5 6 7 1 2 3 

Conclusion

This program effectively rotates an array by k positions using a series of three reverse operations. This approach ensures that the rotation is done in-place, optimizing memory usage while maintaining a time complexity of O(n).

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)