Skip to content

Instantly share code, notes, and snippets.

@raunaqsingh2020
Created January 8, 2020 09:38
Show Gist options
  • Save raunaqsingh2020/c1133fccff4099edd73d25da30725bdc to your computer and use it in GitHub Desktop.
Save raunaqsingh2020/c1133fccff4099edd73d25da30725bdc to your computer and use it in GitHub Desktop.
Shifting
import java.util.*;
public class shifting
{
public shifting()
{
Scanner sc = new Scanner(System.in);
int[] sample = {1,2,3,4,5};
System.out.println("Array: " + Arrays.toString(sample));
System.out.println("Shift by how many?");
int shiftInt = sc.nextInt();
System.out.println("To the Right or Left? (Type 'R' or 'L')");
String direction = sc.next();
boolean right = true;
if(direction.equals("L"))
right = false;
System.out.println(Arrays.toString(shift(sample , shiftInt, right)));
}
public int[] shift(int[] y, int shift, boolean toRight)
{
if(toRight){
y = shiftRight(y, shift);
}else{
y = shiftLeft(y, shift);
}
return y;
}
public int[] shiftRight(int[] y, int shift){
for(int j=0; j<shift; j++){
for(int i = y.length-1; i>0; i--){
int temp = y[i];
y[i]= y[i-1];
y[i-1]=temp;
}
}
return y;
}
public int[] shiftLeft(int[] y, int shift){
for(int j=0; j<shift; j++){
for(int i = 0; i<y.length-1; i++){
int temp = y[i+1];
y[i+1]= y[i];
y[i]=temp;
}
}
return y;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment