Rotate an array - Java Collection Framework

Java examples for Collection Framework:Array Reverse

Description

Rotate an array

Demo Code


//package com.java2s;

public class Main {
    /** Rotate an array, see std::rotate */
    public static <T> void rotate(T[] ray, int first, int new_first,
            int last) {
        int next = new_first;
        while (next != first) {
            T temp = ray[first];//from w  ww.  j a  va2  s. c o m
            ray[first] = ray[next];
            ray[next] = temp;
            first++;
            next++;
            if (next == last) {
                next = new_first;
            } else if (first == new_first) {
                new_first = next;
            }
        }
    }

    /** Rotate an array, see std::rotate */
    public static void rotate(int[] ray, int first, int new_first, int last) {
        int next = new_first;
        while (next != first) {
            int temp = ray[first];
            ray[first] = ray[next];
            ray[next] = temp;
            first++;
            next++;
            if (next == last) {
                next = new_first;
            } else if (first == new_first) {
                new_first = next;
            }
        }
    }

    /** Rotate an array, see std::rotate */
    public static void rotate(float[] ray, int first, int new_first,
            int last) {
        int next = new_first;
        while (next != first) {
            float temp = ray[first];
            ray[first] = ray[next];
            ray[next] = temp;
            first++;
            next++;
            if (next == last) {
                next = new_first;
            } else if (first == new_first) {
                new_first = next;
            }
        }
    }
}

Related Tutorials