Example:
Assume array is
[ 1, 2, 3, 4, 5 ]
Do 1 – Left rotation ie, First Element should move to last, and hence all other items position should push to previous position
Expected Result: [ 2, 3, 4, 5, 1 ]
Algorithm:
Step 1:
store first element to temp;
Step 2:
loop element from start index, fetch next element into current index till the SIZE – 1 element ie., 4th element.
JUMP to step 2 until the iteration number reaches SIZE – 1 :
Step 3:
save temp item (from step 1) as last item in the array.
Logic:
for given array:
array = [ 1, 2, 3, 4, 5 ],
int temp = array [0]; // Step 1 int index = 0; for ( index = 0; index < array.length - 1; index ++ ) // Step 2 array [ index ] = array [ index + 1 ]; array [ index ] = temp; // Step 3
Now, array holds : [ 2, 3, 4, 5, 1 ]
Happy Reading post !!

Leave a comment