Rotate Array in place

/***
Rotate a one-dimensional array of n elements to the right by k steps.
For instance, with n=7 and k=3,
the array {a, b, c, d, e, f, g} is rotated to {e, f, g, a, b, c, d}.
***/
//best performance: time: O(n) and memory: O(1)
//reverse

#include<iostream>

using namespace std;

void swap(char *c1, char *c2) {
       char t = *c1;
       *c1 = *c2;
       *c2 = t;
}

void reverse(char *a, int st, int ed) {
       if(st >= ed) return;

       swap(a+st, a+ed);
       reverse(a, st+1, ed-1);
}

void rotate(char *a, int sz, int k) {

       if (k>sz) return;

       reverse(a, 0, sz-1);
       reverse(a, 0, k-1);
       reverse(a, k, sz-1);

}

void main() {
       char a[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
       rotate(a, 7, 1);
       for (int i = 0; i<7; i++)
              cout<<a[i]<<", ";
       cout<<endl;

}

Comments

Popular posts from this blog

Sudoku

Longest prefix matching - trie

Climbing Stairs