天天看點

将一組數組向右移動k位,末尾的要轉置移動到數組開始,其中n為數組大小,0<k<n

下面是使用a數組本身完成:

package 數組元素k位右移;

/**
 * 數組向又移動k位。 0<k<n
 * 
 * @author SeeClanUkyo 将一組數組向右移動k位,末尾的要轉置移動到數組開始,其中n為數組大小,0<k<n
 */
public class ArrayMoveK {

    public static void main(String[] args) {

        int k = 3;
        int[] a = { 1, 2, 3, 4, 5 };

        arrayMoveK(a, k);
        

    }

    public static void arrayMoveK(int[] a, int k) {

        //擷取長度
        int l = a.length;
        //擷取最大下标值
        int maxIndex = l - 1;
        //for循環使末尾及開始更換位置
        for (int i = 0; i < k; i++) {
            //擷取數組最大下标的數值
            int last = a[maxIndex];
            for (int j = 0; j < maxIndex; j++) {
                //将數組中的其他元素都右移一位 , 第一次擷取時,maxIndex-j為-0為maxIndex本身
                a[maxIndex - j] = a[maxIndex - 1 - j];
            }
            //将本次最末尾的數值傳遞給數組開始
            a[0] = last;
        }
        //周遊輸出新的數組
        for (int x : a) {
            System.out.print(x + " ");
        }
    }

}      

下面是借助第二個數組:(這樣的話就簡單的多了)

package 數組元素k位右移;

/**
 * 數組向又移動k位。 0<k<n
 * 
 * @author SeeClanUkyo 将一組數組向右移動k位,末尾的要轉置移動到數組開始,其中n為數組大小,0<k<n
 */
public class ArrayMoveK {

    public static void main(String[] args) {

        int k = 3;
        int[] a = { 1, 2, 3, 4, 5 };

        arrayMoveK(a, k);
        

    }

    public static void arrayMoveK(int[] a, int k) {

        //擷取長度
        int l = a.length;
        //擷取最大下标值
        int maxIndex = l - 1;
        //for循環使末尾及開始更換位置
        for (int i = 0; i < k; i++) {
            //擷取數組最大下标的數值
            int last = a[maxIndex];
            for (int j = 0; j < maxIndex; j++) {
                //将數組中的其他元素都右移一位 , 第一次擷取時,maxIndex-j為-0為maxIndex本身
                a[maxIndex - j] = a[maxIndex - 1 - j];
            }
            //将本次最末尾的數值傳遞給數組開始
            a[0] = last;
        }
        //周遊輸出新的數組
        for (int x : a) {
            System.out.print(x + " ");
        }
    }

}      

将程式設計看作是一門藝術,而不單單是個技術。

敲打的英文字元是我的黑白琴鍵,

思維圖紙畫出的是我編寫的五線譜。

當美妙的華章響起,現實通往二進制的大門即将被打開。

繼續閱讀