Created
August 16, 2015 19:10
-
-
Save kedarmhaswade/510fc87232e7b2056049 to your computer and use it in GitHub Desktop.
Rotate an Array
This file contains hidden or 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
/** | |
* http://web.stanford.edu/class/cs9/lectures/Coding%20Drill%203.pdf | |
* Problem One: Array Rotation | |
* Your job is to write a function | |
* void rotateArray(int* array, size_t n, size_t amount) | |
* that accepts as input an array and a “rotation amount.” You should then “rotate” the array | |
* by cyclically shifting all of the elements in the array to the left by a number of steps | |
* given by the rotation amount. As an example, suppose we have this array: | |
* 103 106 107 108 109 110 140 161 | |
* Rotating it to the left by three steps would yield this array: | |
* 108 109 110 140 161 103 106 107 | |
* (The input array may or may not be sorted.) | |
* Then, analyze the bigO time and space complexity of your code. | |
*/ | |
class RotateArray { | |
public static void main(String[] args) { | |
int[] a = {103,106,107,108,109,110,140,161}; | |
rotate(a, 11); | |
System.out.println(java.util.Arrays.toString(a)); | |
int[] b = {112,109,110,161}; | |
rotate(b, 2); | |
System.out.println(java.util.Arrays.toString(b)); | |
int[] c = {112,109,110,161}; | |
rotate(b, 4); | |
System.out.println(java.util.Arrays.toString(c)); | |
} | |
static void rotate(int[] a, int ra) { | |
int len = a.length; | |
ra = ra % len; | |
if (ra < 0) | |
throw new IllegalArgumentException("negative ra not allowed: " + ra); | |
if (ra == 0) | |
return; | |
int nr = 0; // number of elements to rotate | |
// boundary: nr == len i.e. all elements are rotated | |
int i = 0; | |
int start = i; // we start with first element | |
int m = a[i]; // remember it first | |
while (true) { | |
int di = i - ra; // the destiation index | |
if (di < 0) | |
di = len - (-di); | |
int tmp = a[di]; | |
a[di] = m; | |
m = tmp; | |
i = di; // destination is the new source | |
nr += 1; | |
if (nr == len) | |
break; | |
if (i == start) { // ra divides len evenly, and we are not yet done! | |
System.out.println("back at: " + i + ", but we aren't done yet"); | |
i = (i+1) % len; | |
start = i; | |
m = a[start]; | |
} | |
//System.out.println(java.util.Arrays.toString(a)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment