Algo.Java.ShiftArray

// right

(i+x) % array.length

// left

(i - x + n) % array.length

// left

public static int[] shiftArrayLeft(int[] arr, int x) {
        int n = arr.length;
        int[] shiftedArray = new int[n];

        for (int i = 0; i < n; i++) {
            // Calculate the new position using the formula
            int newPos = (i - x + n) % n;
            shiftedArray[newPos] = arr[i];
        }

        return shiftedArray;
    }

// right

    public static int[] shiftArrayRight(int[] arr, int x) {
        int n = arr.length;
        int[] shiftedArray = new int[n];

        for (int i = 0; i < n; i++) {
            // Calculate the new position using the formula
            int newPos = (i + x) % n;
            shiftedArray[newPos] = arr[i];
        }

        return shiftedArray;
    }
This entry was posted in Без рубрики. Bookmark the permalink.