简单的伪代码代码问题

发布于 2024-09-16 13:56:02 字数 238 浏览 5 评论 0原文

我对伪代码有点陌生。我理解代码的意思,但很难将各个部分组合在一起。我应该如何思考来理解这段代码在做什么:

假设 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

请恋爱 2024-09-23 13:56:02

好吧,

1 for p := 1 to ⌊k/2⌋

这意味着我们要到达阵列的一半。

2 t := ap
3 ap := ak−p+1
4 ak−p+1 := t

该模式可以被识别为“与临时 t 的交换”。以及交换了什么?

嗯,apak-p+1,其中一个是数组开始的第 p 个元素,另一个是倒数第 p

总结一下

将第一个 n 与最后一个 n 数组值交换,直到数组的一半。然后呢? 数组颠倒了

请注意,您的伪代码格式看起来非常奇怪 - 而且最重要的是 - 含糊不清。

ak-p+1 等于 a[k-p+1]a[k]-p+1>a[kp]+1?如果没有,其他的你是怎么表达的?

因此,首先,我会将这段代码转换为实际的源代码,例如 Python 的源代码,这样更容易阅读。

编辑

I)嗯,正如您所发布的,数组范围从 a1ak

II) 思考如何交换两个变量(ab)的值:

1 temp := a
2 a    := b
3 b    := temp

当然,因为您用 覆盖了 a b 在第 2 行中,您必须将旧的 a 值存储在临时值中,即 temp

Ookay,

1 for p := 1 to ⌊k/2⌋

means, we're going up to the half of the array.

2 t := ap
3 ap := ak−p+1
4 ak−p+1 := t

This pattern can be recognized as a "swap with temporary t". And what is swapped?

Well, ap and ak-p+1, one being the p-th element from the array start, the other one the p-th one from the end.

So, to sum up:

You swap the n-th first with the n-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 to a[k-p+1] or to a[k]-p+1 or a[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 to ak.

II) Think how you could swap the values of two variables (a and b):

1 temp := a
2 a    := b
3 b    := temp

Of course, since you overwrote a with b in line 2, you had to store the old a value in a temporary, which is temp.

滥情空心 2024-09-23 13:56:02

当循环将 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文