left shift array java code example

Example 1: shift elements in array java

// Shift right from index of 'a' to 'b'
for(int i = b; i>a; i--) { array[i] = array[i-1]; }
/* Note: element at 'a' index will remain unchanged */

// Shift left from index of 'b' to 'a' 
for(int i = a; i<b; i++) { array[i] = array[i+1]; }
/* Note: element at 'b' index will remain unchanged */

Example 2: array rotation program in java

//Rotating array left 
//d = number of rotations
static void rotLeft(int[] a, int d)
{
    //using secondary array of  same size 
	int [] n = new int[a.length];
    //saving element into array n[] according to newlocation of rotations(d)
	for(int i = 0; i < a.length; i++)
	{
		int newlocation = (i+(a.length - d))% a.length;
		n[newlocation] = a[i];
	}
	//printing new rotated array
	for(int i = 0; i < a.length; i++)
	{
		System.out.print(n[i]+ " ");
	}
}

Tags:

Java Example