Skip to content

Instantly share code, notes, and snippets.

@rounakdatta
Created February 27, 2019 18:36
Show Gist options
  • Save rounakdatta/c80a1894f7109868a3379f005d3de24f to your computer and use it in GitHub Desktop.
Save rounakdatta/c80a1894f7109868a3379f005d3de24f to your computer and use it in GitHub Desktop.
An efficient algorithm to left-rotate an array by k
#include <iostream>
using namespace std;
void reverseArray(int *array, int start, int end) {
for (int i = start, j = end - 1; i < j; i++, j--) {
array[i] = array[i] ^ array[j];
array[j] = array[i] ^ array[j];
array[i] = array[i] ^ array[j];
}
}
// most efficient algorithm
void leftRotate(int *array, int n, int k) {
// reverse the first part of the array (upto k)
reverseArray(array, 0, k);
// reverse the second part
reverseArray(array, k, n);
// then the entire one
reverseArray(array, 0, n);
}
int main() {
int myArray[] = {1, 2, 3, 4, 5, 6, 7};
int n = sizeof(myArray) / sizeof(myArray[0]);
int k = 3;
//reverseArray(myArray, 0, n);
leftRotate(myArray, n, k);
for (int i = 0; i < n; i++) {
cout << myArray[i] << " ";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment