Circular rotation of an array by K positions

Write a program for circular rotation of an array by K positions.

Example:

Input: arr={3,4,2,1,9}
Output: 1 9 3 4 2 

Approach

C++

#include <bits/stdc++.h>
using namespace std;

void circularRotatebyK(vector<int&arrint k)
{
    int n = arr.size();
    k = k % n;
    int temp[k];
    for (int i = 0i < n-ki++)
        temp[i] = arr[i];
    int l = 0;
    for (int i = n-ki < ni++)
        arr[l++] = arr[i];

    for (int i = 0i < n-ki++)
        arr[l++] = temp[i];
}
int main()

{
    vector<intarr = {3,4,2,1,9};
    int k = 2;

    circularRotatebyK(arrk);

    for (int i = 0i < arr.size(); i++)
    {
        cout << arr[i] << " ";
    }
    return 0;
}


No comments:

Post a Comment