集册 Java实例教程 将数组旋转n个位置

将数组旋转n个位置

欢马劈雪     最近更新时间:2020-01-02 10:19:05

515
将数组旋转n个位置
/*from N  o w  J a v a . c o m*/


//package com.nowjava;


public class Main {

    /**

     * 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;
        /* 
         来自 
        *nowjava - 时  代  Java*/

        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] 
展开阅读全文