Array Rotations
Learn and practice how to shift the value in an array.
We'll cover the following...
Rotating an array to the left is one of the most common and complex algorithms involving an array. It rotates the array to the left by the number of elements. Suppose we have an array like this:
{1, 2, 3}
We’ll rotate the array above to the left by one element. Then it becomes like the following array:
{2, 3, 1}
If we rotate it by two elements, it becomes the following:
{3, 1, 2}
Rotating three elements will give us this:
{1, 2, 3}
Left rotation of an array
To understand this rotational algorithm better, we have to create a function that will take two inputs—the array and the array’s length. It will give us the output of a temporary value by shifting one element. After that, we can call that function inside another function that takes three inputs—the array, the array’s length, and the number of elements we want to shift to the left. We can dynamically create any array size and test the code below in any programming language. It will give us the same result. Let’s look at the following code snippet:
//Dartimport "dart:io";void main(){List<int> myNumbers= List(7);myNumbers[0]= 100;myNumbers[1]= 2;myNumbers[2]= 23;myNumbers[3]= 4;myNumbers[4]= 15;myNumbers[5]= 155;myNumbers[6]= 1;int lengthOfArray= myNumbers.length;print("The array before left rotation by two elements: ${myNumbers}");//print("The array after rotation.");stdout.write("The array after rotation: [");rotateArrayLeft(myNumbers,2,lengthOfArray);displayArray(myNumbers,lengthOfArray);}void rotateArrayLeft(List<int> myArray,int rotatingNumbers,int arrayLength){for(int i=0;i<rotatingNumbers;i++){rotateLeftByOne(myArray, arrayLength);}}void rotateLeftByOne(List<int> myArray,int arrayLength){int temp= myArray[0], i;for(i=0;i<arrayLength-1;i++){myArray[i] = myArray[i + 1];}myArray[i]=temp;}void displayArray(List<int> myArray,int arrayLength){for(int i=0;i<arrayLength;i++){//print(myArray[i]);stdout.write(myArray[i]);stdout.write(" ");}stdout.write("] ");}
Here’s the output:
The array before left rotation by two elements: [100, 2, 23, 4, 15, 155, 1]
The array after rotation: [23 4 15 155 1 100 2 ]
In the code above:
- Lines 5–12: We create a
myNumbers
list of seven elements. - Lines 29–32: In the
rotateLeftByOne()
method, we take the list’s first element in thetemp
vriable. After that, we continue assigning the right elements (i.e., to