In my java program I have an array of length 5, I want to shift the contents of the array 3 places to the left. For example [1,2,3,4,5] would become [4,5,1,2,3]. What would be the best way possible to do this? Thanks
Well, you need temporary storage of some description. If you have enough memory, you could do this in one go:
int[] buffer = new int[placesToShift];
// Save the start of the array in the buffer
System.arraycopy(array, 0, buffer, 0, placesToShift);
// Copy the rest of the array into place
System.arraycopy(array, placesToShift, array, 0, array.length - placesToShift);
// Copy the buffer into the end
System.arraycopy(buffer, 0, array, array.length - placesToShift, buffer.length);
It's also worth noting that you can always get by with at most half the array length as a buffer, by treating (say) a "shift left by 4" as a "shift right by 1".
You can do it with constant extra space by repeatedly shifting once. For example:
for (int i = 0; i < placesToShift; i++) {
int firstElement = array[i];
System.arraycopy(array, 1, array, 0, array.length - 1);
array[array.length - 1] = firstElement;
}
That's inefficient in time of course, but efficient in space.
See more on this question at Stackoverflow