Write a Kotlin Program to cyclically rotate array clockwise by one.
Suppose you have an array
val arr = intArrayOf( 10 , 21 , 32 , 42 , 51 ) |
If we want to cyclically rotate that array clockwise by one, output should be something like –
We can do so as below –
- Assume array is of size n.
- At first, store last element of array in a variable temp.
- Then, move all elements to right by one position i.e. move item at n-2th position to n-1th position, item at n-3th position to n-2th position etc. That means, item at ith position will shift to i+1th position.
- After moving all elements to it’s subsequent position, replace first item with value stored in variable temp.
Kotlin program to cyclically rotate item by one –
val arr = intArrayOf( 10 , 21 , 32 , 42 , 51 ) |
val temp = arr[arr.size - 1 ] |
for (curIndex in arr.lastIndex downTo 1 ) { |
arr[curIndex] = arr[curIndex- 1 ] |
println( "\nElements after cyclically rotating array by one: " ) |
When you run above program, you will get below output –
Elements after cyclically rotating array by one: |
Time complexity: O(n), We are iterating through all the elements in array.
That’s how we can write kotlin program to cyclically rotate array by one with example.