add arrays left rotation in java (#155)

pull/168/head
Toihir Halim 2021-04-11 19:49:36 +02:00 committed by GitHub
parent d7860a161e
commit c3db2ee9f9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 52 additions and 0 deletions

View File

@ -20,3 +20,4 @@
1. [Counting Inversions](java/count-inversions.java)
2. [Kadane's Algorithm](java/Kadanes_Algorithm.java)
2. [Left Rotation of Array](java/left_rotation.java)

View File

@ -0,0 +1,51 @@
public class left_rotation{
public static void rotateToLeft(int [] arr){
if(arr == null || arr.length == 0){
System.out.println("no rotation possible");
return;
}
//take the first element
int firstElement = arr[0];
//move everything in the left
for(int i = 0; i < arr.length -1; i++){
arr[i] = arr[i + 1];
}
//the first element become the last element
arr[arr.length - 1] = firstElement;
}
public static void print(int [] arr){
System.out.print("[");
for(int i = 0; i < arr.length; i++)
System.out.print(arr[i] + ", ");
System.out.println("]");
}
public static void main(String [] args){
int [] arr = {1,2,3,4,5,6,7,8,9};
int n = 3; //number of times to rotate the array
System.out.print("before: ");
print(arr);
System.out.println("rotating " + n + " times to left");
for(int i = 0; i < n; i++)
rotateToLeft(arr); //move to left n times
System.out.print("after: ");
print(arr);
}
}
/*
to run the file:
javac left_rotation.java
java left_rotation
result:
before: [1, 2, 3, 4, 5, 6, 7, 8, 9, ]
rotating 3 times to left
after: [4, 5, 6, 7, 8, 9, 1, 2, 3, ]
*/