You are given an array of N items, and a non-negative integer K smaller than N. Your job is to rotate the array (in-place) by K items. So, if the input array contains the characters abcdefgh (so N = 8), and K = 3, then at the end of the routine the array will contain defghabc.
public class PslString {
public static void main(String[] args) {
String str = "abcdefgh";
char[] arr = str.toCharArray();
int len = str.length();
int k = 3;
// It first reverses the first part of array
// i.e. cba
swapping(arr, 0, k);
// It reverses the second part of array
// i.e. jihgfed
swapping(arr, k, len);
// Finally it swaps opposite end elements
swapping(arr, 0, len);
for(char ch : arr) {
System.out.print(ch + " ");
}
}
public static char[] swapping(char[] arr, int start, int end) {
int j = end-1;
for(int i = start; j >= i; i++,j--) {
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
}
}
public class PslString {
public static void main(String[] args) {
String str = "abcdefgh";
char[] arr = str.toCharArray();
int len = str.length();
int k = 3;
// It first reverses the first part of array
// i.e. cba
swapping(arr, 0, k);
// It reverses the second part of array
// i.e. jihgfed
swapping(arr, k, len);
// Finally it swaps opposite end elements
swapping(arr, 0, len);
for(char ch : arr) {
System.out.print(ch + " ");
}
}
public static char[] swapping(char[] arr, int start, int end) {
int j = end-1;
for(int i = start; j >= i; i++,j--) {
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
}
}