views:

94

answers:

2

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
A: 

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.

rics
Hmm ok. So what does this really mean? When I ran some numbers in there, it seemed like it would take a[k]-1 and it would decrement it by one each time the loop ran.
fprime
+2  A: 

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.

Dario
this is a very bad pseudo code notation. How can one know it ak-p+1 means a[k-p+1] or a[k] - p + 1.
Dave
I'm very new to programming so recognizing these patterns is not common sense to me, yet. What exactly does 'swap with temporary t' mean? Also, at what value does the array start and what value does the array stop?
fprime
Edited the question. Go step by step!
Dario