Simple Pseudocode Code Question

心不动则不痛 提交于 2019-12-11 15:48:35

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3595256/simple-pseudocode-code-question

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!