原始数据:
a(1) |
a(2) |
a(3) |
a(4) |
1 |
2 |
3 |
4 |
方法一:
①向右旋转1步:
a(1) |
a(2) |
a(3) |
a(4) |
4 |
1 |
2 |
3 |
②向右旋转2步:
a(1) |
a(2) |
a(3) |
a(4) |
3 |
4 |
1 |
2 |
③向右旋转3步:
a(1) |
a(2) |
a(3) |
a(4) |
2 |
3 |
4 |
1 |
方法二:
①将a(1)值放至旋转3个位置后位置a(4):
a(1) |
a(2) |
a(3) |
a(4) |
1 |
2 |
3 |
1 |
②将原a(4)值放至旋转3个位置后位置a(3):
a(1) |
a(2) |
a(3) |
a(4) |
1 |
2 |
4 |
1 |
③将原a(3)值放至旋转3个位置后位置a(2):
a(1) |
a(2) |
a(3) |
a(4) |
1 |
3 |
4 |
1 |
④将原a(2)值放至旋转3个位置后位置a(1):
a(1) |
a(2) |
a(3) |
a(4) |
2 |
3 |
4 |
1 |
有n个数存储在数组a中,给定一个整数p(1≤p≤n),将数组a的前p个数与后n-p个数分别向右旋转k次。例如数组a的各个数值分别是1,2,3,4,5,6,7,当p=4,k=1时,旋转后的结果为4,1,2,3,7,5,6。小明为此编写了VB程序,功能如下:在文本框Text2、Text3中依次输入p和k的值,单击“旋转数组”按钮Command1后,数组旋转后结果显示在Text4中。程序运行界面如图1所示,请回答下列问题:
图1
Dim a(20) As Integer
Const n = 20
Private Sub Form_Load()
'随机产生n个[1,100]之间的随机整数,依次存储到a(1)、a(2)、…a(n)中,并在文本框Text1显示,代码略
End Sub
Private Sub Command1_Click()
Dim i As Integer, p As Integer, k As Integer,cnt As Integer,c As Integer,t As Integer
p = Val(Text2.Text)
k = Val(Text3.Text)
i = 1:start = 1:c = a(i):cnt = 1
Do While cnt<= p '方法二
i =
t = a(i)
a(i) = c
If Then
start = start + 1
i = i + 1
c = a(i)
Else
c = t
End If
cnt = cnt + 1
Loop
For i = 1 To k '方法一
temp = a(n)
For j =
a(j) = a(j - 1)
Next j
a(p + 1) = temp
Next i
For i = 1 To n
s = s + Str(a(i))
Next i
Text4.Text = s
End Sub