Rotates an array by n positions - Java Collection Framework

Java examples for Collection Framework:Array Reverse

Description

Rotates an array by n positions

Demo Code


//package com.java2s;

public class Main {
    /**/*from  w  w  w. ja  v  a  2 s .c  o  m*/
     * Rotates an array by n positions
     * @param list
     * @param n
     * @return
     */
    public static void rotateArray(Integer[] list, int n) {
        for (int k = 0; k < list.length / n; k++) {
            for (int i = 0; i < n; i++) {
                int temp = list[i + k * n];
                list[i + k * n] = list[list.length - n + i];
                list[list.length - n + i] = temp;
            }
        }
    }

    /**
     * Rotates an array by n positions
     * @param list
     * @param n
     * @return
     */
    public static void rotateArray(Character[] list, int k) {

        int n = k % list.length;
        int fromPos;
        char temp;
        if (n > list.length / 2)
            fromPos = list.length - n;
        else
            fromPos = 0;
        temp = list[fromPos];
        char temp2 = 'z';
        for (int count = 0; count < list.length; count++) {
            int toPos = n + fromPos;
            toPos = (toPos > list.length - 1) ? toPos - list.length : toPos;
            if (count != 0 && list[toPos] == temp2) {
                toPos += 1;
                fromPos = toPos;
                count--;
                temp = list[fromPos];
            } else {
                temp2 = list[toPos];
                list[toPos] = temp;
                fromPos = toPos;
                temp = temp2;
            }
        }
    }
}

Related Tutorials