shift
is a static method of the ArrayUtils
class that shifts the elements in an array in the clockwise or anti-clockwise direction by an offset.
shift
operation is in-place in nature, i.e., the modification is done to the original array.(offset) modulo (length of the array)
.Application of the shift
function will result in the following array:
[4,5,1,2,3]
.
As the offset is positive, the rotation/shift is in the clockwise direction. The last two elements are moved to the beginning of the array.
Application of the shift
function will result in the following array:
[3,4,5,1,2]
.
As the offset is negative, the rotation/shift is in the anti-clockwise direction. The first two elements are moved to the end of the array.
Application of the shift
function will result in the following array:
[2,3,4,5,1]
.
As the offset is positive, the rotation/shift is in the clockwise direction. Here, the effective offset value is 34 % 5 = 4
. The last four elements of the array are moved to the beginning of the array.
ArrayUtils
is defined in theApache Commons Lang
package. To addApache Commons Lang
to the Maven Project, add the following dependency to thepom.xml
file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the Maven Repository.
You can import the
ArrayUtils
class as follows.
import org.apache.commons.lang3.ArrayUtils;
public static void shift(final int[] array, final int offset)
final int[] array
: the arrayfinal int offset
: the numbers of positions to rotate/shift the elementsThe method doesn’t return anything as the shifting is done to the original array that is passed as an argument.
import org.apache.commons.lang3.ArrayUtils;public class Main {public static void main( String args[] ) {int[] array = {1,2,3,4,5};System.out.print("Original Array - ");for(int i: array){System.out.print(i + " ");}ArrayUtils.shift(array, 34);System.out.print("\nModified Array after shifting - ");for(int i: array){System.out.print(i + " ");}}}
Original Array - 1 2 3 4 5
Modified Array after shifting - 2 3 4 5 1