第2章 数字之魅——数组循环移位

数组循环移位

问题描述

分析与解法

  假如数组为abcd1234,循环右移4位的话,我们希望到达的状态是1234abcd。不妨设K是一个非负的整数,当K为负整数的时候,右移K位,想当于左移(-K)位。左移和右移在本质上是一样的。

【解法一】

 

详细代码如下:

 1 package chapter2shuzizhimei.xunhuanyiwei;
 2 /**
 3  * 数组循环移位
 4  * @author DELL
 5  *
 6  */
 7 public class XunHuanYiWei {
 8     //移位算法,右移k位
 9     public static void rightShift(double a[],int n, int k){
10         k %= n;
11         while(k!=0){
12             double temp = a[n-1];
13             for(int i=n-1;i>0;i--){
14                 a[i]=a[i-1];
15             }
16             a[0] = temp;
17             k--;
18         }
19     }
20     public static void main(String[] args) {
21         double a[] = {1,2,3,4,5,6};
22         System.out.print("移位前的数组为:");
23         for(int i=0;i<a.length;i++){
24             System.out.print(a[i]+" ");
25         }
26         System.out.println();
27         rightShift(a,a.length,3);
28         System.out.print("移位后的数组为:");
29         for(int i=0;i<a.length;i++){
30             System.out.print(a[i]+" ");
31         }
32         System.out.println();
33     }
34 
35 }

程序运行结果如下:

移位前的数组为:1.0 2.0 3.0 4.0 5.0 6.0 
移位后的数组为:4.0 5.0 6.0 1.0 2.0 3.0 

【解法二】

 

详细代码如下:

 

 1 package chapter2shuzizhimei.xunhuanyiwei;
 2 /**
 3  * 数组循环移位
 4  * 【解法二】
 5  * @author DELL
 6  *
 7  */
 8 public class XunHuanYiWei2 {
 9     //实现逆序
10     public static void reverse(double a[], int b, int e){
11         while(b<e){
12             double temp = a[e];
13             a[e] = a[b];
14             a[b] = temp;
15             b++;
16             e--;
17         }
18     }
19     //移位算法,右移k位
20     public static void rightShift(double a[],int n, int k){
21         k %= n;
22         reverse(a, 0, n-k-1);
23         reverse(a, n-k, n-1);
24         reverse(a, 0, n-1);
25     }
26     public static void main(String[] args) {
27         double a[] = {1,2,3,4,5,6};
28         System.out.print("移位前的数组为:");
29         for(int i=0;i<a.length;i++){
30             System.out.print(a[i]+" ");
31         }
32         System.out.println();
33         rightShift(a,a.length,3);
34         System.out.print("移位后的数组为:");
35         for(int i=0;i<a.length;i++){
36             System.out.print(a[i]+" ");
37         }
38         System.out.println();
39     }
40 
41 }

程序运行结果如下:

移位前的数组为:1.0 2.0 3.0 4.0 5.0 6.0 
移位后的数组为:4.0 5.0 6.0 1.0 2.0 3.0 

 

posted @ 2015-07-09 09:52  ~风轻云淡~  阅读(238)  评论(0编辑  收藏  举报