on Leave a Comment

Left Rotation of Array in Java

In this article, w will see how to rotate elements of array on left  hand side.

First, we ask the user to enter length of array and number of left rotation. For example, if user enters 3 left rotation for [1, 2, 3, 4, 5] then output will be [4, 5, 1, 2, 3]. Length and number of left rotation can't be a floating point number.

Steps:

Here is length of array and is number of left rotation of array.

- Store the first array element in temp variable.
- Shift the array elements on left side by

for(i=0; i<n-1; i++){
   arr[i] = arr[i+1];
}

- Then assign the temp value to arr[n-1]
- Repeat above steps r times.

Java Program to Left Rotation of Array

import java.util.Scanner;
public class LeftRotation{
 public static void main(String[] args){
  int temp, i, r, j, n;
  Scanner sc = new Scanner(System.in);
  System.out.print("Enter Length of Array: ");
  n = sc.nextInt();
  System.out.print("Enter Number of Left Rotation Array: ");
  r = sc.nextInt();
  int[] arr = new int[n];
  System.out.print("Enter Array Elements: ");
  for(i=0; i<n; i++)
   arr[i] = sc.nextInt();
  for(j=0; j<r;j++){
   temp = arr[0];
   for(i=0; i<n-1; i++){
    arr[i] = arr[i+1];
   }
   arr[n-1]=temp;
  }
  System.out.print("Elements are ");
  
  for(int a:arr){
  System.out.print(a+" ");
  }
  
 }
}

Output:

Enter Length of Array: 5
Enter Number of Left Rotation Array: 3
Enter Array Elements: 1 2 3 4 5
Elements are 4 5 1 2 3



0 comments:

Post a Comment