Shift Array Elements in Java


 

Shift Array Elements in Java

This section illustrates you how to shift the array elements in a circular way.

This section illustrates you how to shift the array elements in a circular way.

Java Shift Array Elements

This section illustrates you how to shift the array elements in a circular way. For this, first of all, we have allowed the user to enter the array elements,  the direction of shifting (Right or Left) and also the number of times the array will be shifted. When the user enters the direction of shifting and the times of shifting, corresponding method will be called accordingly and displayed the array with shifted elements.

Method that shift the elements from left:

public static void shiftLeft(int[] array, int amount) {
		for (int j = 0; j < amount; j++) {
			int a = array[0];
			int i;
			for (i = 0; i < array.length - 1; i++)
				array[i] = array[i + 1];
			array[i] = a;
		}
	}

Method that shift the elements from right:

public static void shiftRight(int[] array, int amount) {
		for (int j = 0; j < amount; j++) {
			int a = array[array.length - 1];
			int i;
			for (i = array.length - 1; i > 0; i--)
				array[i] = array[i - 1];
			array[i] = a;
		}
	}

Here is the code:

import java.util.Scanner;

public class ShiftArrayValues {
	public static void main(String[] args) {
		int[] array = new int[10];
		System.out.println("Enter 10 numbers");
		Scanner input = new Scanner(System.in);
		for (int i = 0; i < array.length; i++) {
			array[i] = input.nextInt();
		}
		System.out.println("Original array is:");
		printArray(array);
		System.out.println();
		System.out.println("Left or Right");
		String st = input.next();
System.out.print("Enter an amount by which to rotate the array: ");
		int amount = input.nextInt();
		if (st.equals("Left")) {
			shiftLeft(array, amount);
			System.out.print("Resulted Array is: ");
			printArray(array);
		} else if (st.equals("Right")) {
			shiftRight(array, amount);
			System.out.print("Resulted Array is: ");
			printArray(array);
		}
	}

	public static void shiftLeft(int[] array, int amount) {
		for (int j = 0; j < amount; j++) {
			int a = array[0];
			int i;
			for (i = 0; i < array.length - 1; i++)
				array[i] = array[i + 1];
			array[i] = a;
		}
	}

	public static void shiftRight(int[] array, int amount) {
		for (int j = 0; j < amount; j++) {
			int a = array[array.length - 1];
			int i;
			for (i = array.length - 1; i > 0; i--)
				array[i] = array[i - 1];
			array[i] = a;
		}
	}

	public static void printArray(int[] array) {
		for (int x = 0; x < array.length; x++) {
			System.out.print(array[x] + " ");
		}
		System.out.println();
	}
}

Output

Enter 10 numbers
1
2
3
4
5
6
7
8
9
12
Original array is:
1 2 3 4 5 6 7 8 9 12

Left or Right
Left
Enter an amount by which to rotate the array: 3
Resulted Array is: 4 5 6 7 8 9 12 1 2 3

Ads