Rotates array using classic three reversals - Java Collection Framework

Java examples for Collection Framework:Array Reverse

Description

Rotates array using classic three reversals

Demo Code


//package com.java2s;

public class Main {
    /**/*from   w ww .ja va2 s.c om*/
     * Rotates array using classic three reversals
     * @param list
     * @param k
     */
    public static void rotateArrayReversal(Character[] list, int k) {
        int n = k % list.length;
        reverseArrayFromToPosition(list, 0, list.length - 1);
        reverseArrayFromToPosition(list, 0, n - 1);
        reverseArrayFromToPosition(list, n, list.length - 1);
    }

    public static void reverseArrayFromToPosition(Character[] list,
            int fromPos, int toPos) {
        //System.out.println("from Pos: " + fromPos + " to Pos" + toPos);
        int numIterations = (int) Math.ceil((toPos - fromPos) / 2.0);
        for (int x = fromPos; x < fromPos + numIterations; x++) {
            char temp = list[x];
            list[x] = list[toPos + fromPos - x];
            list[toPos + fromPos - x] = temp;
        }
    }
}

Related Tutorials