我从来没有太多需要编写大量正式的伪代码,但需求已经出现,所以我想我会选择一些标准来保持代码间的一致性。一些麻省理工学院课件伪代码
为此,我拿起了一些“iTunes U”课件视频,其中包括6.046J/18.410J Introduction to Algorithms (SMA 5503)。
在最初的讲座视频,讲师在黑板上写道:插入排序,和他写的:
Insertion-Sort(A, N) // Sorts A[1..n]
for j ← 2 to n
do key ← A[j]
i ← j-1
while i > 0 and A[i] > key
do A[i+1] ← A[i]
i ← i-1
A[i+1] ← key
所以,我的问题:
- 为什么
i ← j-1
时A[i+1] = key
?也就是说,为什么←
在某些情况下和=
在另一个?请注意,在上面的代码中,←
也用于后者,但在网络上提供的讲义中使用=
,这是否仅仅是一个错字? (我是这么认为的) - 更重要,为什么
do key ← A[j]
i ← j-1
?什么是特别的,它需要一个do
这样的命令,并缩进?
换句话说,为什么不是这样写的(我的亮点)上面的伪代码:
Insertion-Sort(A, N) // Sorts A[1..n]
for j ← 2 to n
key ← A[j] <-- lost the do here
i ← j-1 <-- no indentation
while i > 0 and A[i] > key
A[i+1] ← A[i] <-- lost the do here
i ← i-1 <-- no indentation
A[i+1] ← key
最后一个问题:有没有人有一个编码标准的伪代码方便的地方?我的主要目标是一致性,所以我只需要“教”一次收件人。