Home > Software design >  Shift array elements by n posisition
Shift array elements by n posisition

Time:03-30

I've got method to move elements in array, move to right work fine, move to left work incorrect. Method get two incoming parameters:

1st: array

2nd: int variable to move element on this int parameter.

Here is my method:

private static int[] arrShift(int[]arr, int count) {
    if (count >= 0) {
        for (int i = 0; i < count; i  ) {
            int temp = arr[arr.length - 1];
            for (int j = arr.length - 2; j > -1; j--) {
                arr[j   1] = arr[j];
            }
            arr[0] = temp;
        }
    }
    if (count < 0){
        count *=-1;
        int temp = arr[0];
        for (int i = 0; i < count; i  ) {
            for (int j = 0; j < arr.length -1; j  ) {
                arr[j] = arr[j   1];
            }
        }
        arr[0] = temp;
    }
    return arr;
}

How shift elements to left?

CodePudding user response:

This should work like a charm :)

private static int[] arrShift(int[]arr, int count) {
    if (count >= 0) {
        for (int i = 0; i < count; i  ) {
            int temp = arr[arr.length - 1];
            for (int j = arr.length - 2; j > -1; j--) {
                arr[j   1] = arr[j];
            }
            arr[0] = temp;
        }
    }
    if (count < 0){
        count *=-1;
        for (int i = 0; i < count; i  ) {
            int temp = arr[0];
            for (int j = 0; j < arr.length -1; j  ) {
                arr[j] = arr[j   1];
            }
            arr[arr.length - 1] = temp;
        }
    }
    return arr;
}
  • Related