简单的伪代码代码问题
我对伪代码有点陌生。我理解代码的意思,但很难将各个部分组合在一起。我应该如何思考来理解这段代码在做什么:
假设 a1, a2, . 。 。 , ak 是 k 个数字的数组。以下是什么意思 代码片段呢?简单解释一下原因。假设所有缩进行 属于循环内部。
1 for p := 1 to ⌊k/2⌋
2 t := ap
3 ap := ak−p+1
4 ak−p+1 := t
I'm a little new to pseudocode. I understand what the code is saying, but having a hard time putting the pieces together. How should I be thinking to understand what this code is doing:
Suppose that a1, a2, . . . , ak is an array of k numbers. What does the following
code fragment do? Briefly explain why. Assume that all the indented lines
belong inside the loop.
1 for p := 1 to ⌊k/2⌋
2 t := ap
3 ap := ak−p+1
4 ak−p+1 := t
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,
这意味着我们要到达阵列的一半。
该模式可以被识别为“与临时
t
的交换”。以及交换了什么?嗯,
ap
和ak-p+1
,其中一个是数组开始的第p
个元素,另一个是倒数第p
个。总结一下:
将第一个
n
与最后一个n
数组值交换,直到数组的一半。然后呢? 数组颠倒了。请注意,您的伪代码格式看起来非常奇怪 - 而且最重要的是 - 含糊不清。
ak-p+1
等于a[k-p+1]
或a[k]-p+1
或>a[kp]+1
?如果没有,其他的你是怎么表达的?因此,首先,我会将这段代码转换为实际的源代码,例如 Python 的源代码,这样更容易阅读。
编辑。
I)嗯,正如您所发布的,数组范围从
a1
到ak
。II) 思考如何交换两个变量(
a
和b
)的值:当然,因为您用
覆盖了
在第 2 行中,您必须将旧的a
ba
值存储在临时值中,即temp
。Ookay,
means, we're going up to the half of the array.
This pattern can be recognized as a "swap with temporary
t
". And what is swapped?Well,
ap
andak-p+1
, one being thep
-th element from the array start, the other one thep
-th one from the end.So, to sum up:
You swap the
n
-th first with then
-th last array value up to the half of the array. And afterwards? The array is reversed.Note that your pseudocode-format looks really weird - and, most importantly - ambiguous.
Is
ak-p+1
equivalent toa[k-p+1]
or toa[k]-p+1
ora[k-p]+1
? If not, how did you express the other ones.So at first, I'll convert this code to an actual source like Python's, which is much easier to read.
Edit.
I) Well, as you posted, the array ranges from
a1
toak
.II) Think how you could swap the values of two variables (
a
andb
):Of course, since you overwrote
a
withb
in line 2, you had to store the olda
value in a temporary, which istemp
.当循环将 a[p] 更改为 a[k-p+1] 时,循环将数组镜像到其中心元素,其中 a[p] 始终位于数组的“左侧”,而 a[k-p+1]总是在“正确”的一边。
t 是一个临时变量。
The loop mirrors the array to its central element as it changes a[p] with a[k-p+1] where a[p] is always on the "left" side of the array and a[k-p+1] is always on the "right" side.
t is a temporary variable.