Created
May 18, 2014 16:03
-
-
Save lisaah/e1c7022436953481192d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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