Skip to content

Instantly share code, notes, and snippets.

@lisaah
Created May 18, 2014 16:03
Show Gist options
  • Save lisaah/e1c7022436953481192d to your computer and use it in GitHub Desktop.
Save lisaah/e1c7022436953481192d to your computer and use it in GitHub Desktop.
// Rotate an array to right by n.
function rotate(a, n) {
// Convert negative to positive.
if (n < 0) n = ((n % a.length) + a.length);
n = n % a.length;
reverse(a, 0, a.length); // Move to bottom to reverse to the left.
reverse(a, 0, n);
reverse(a, n, a.length);
}
// Reverse the subarray.
function reverse(a, start, end) {
var temp;
var mid = start + ((end - start)/2 | 0); // Round to int.
for (var i = start; i < mid; i++) {
temp = a[i];
a[i] = a[start + end - i - 1];
a[start + end - i - 1] = temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment