算法导论中的插入排序
在算法简介第二版中,我找到了插入排序伪代码,
INSERTION-SORT(A)
1 for j <- 2 to length[A]
2 do key <- A[j]
3 //Insert A[j] into the sorted sequence A[1 □ j - 1].
4 i <- j - 1
5 while i > 0 and A[i] > key
6 do A[i+1] <- A[i]
7 i <- i -1
8 A[i + 1] <- key
但我无法理解交换在这里是如何工作的。
我认为它需要像这样的交换操作,
INSERTION-SORT(A)
1 for j <- 2 to length[A]
2 do key <- A[j]
3 //Insert A[j] into the sorted sequence A[1 □ j - 1].
4 i <- j - 1
5 while i > 0 and A[i] > key
6 do temp <- A[i+1]
7 A[i+1] <- A[i]
8 A[i] <- temp
9 i <- i -1
10 A[i + 1] <- key
我做错了什么吗? 请帮忙
in an Introduction to Algorithm 2nd edition, I found insertion sort pseudo code
INSERTION-SORT(A)
1 for j <- 2 to length[A]
2 do key <- A[j]
3 //Insert A[j] into the sorted sequence A[1 □ j - 1].
4 i <- j - 1
5 while i > 0 and A[i] > key
6 do A[i+1] <- A[i]
7 i <- i -1
8 A[i + 1] <- key
but I can't understand how swap works here.
I think it needs a swap operation like this
INSERTION-SORT(A)
1 for j <- 2 to length[A]
2 do key <- A[j]
3 //Insert A[j] into the sorted sequence A[1 □ j - 1].
4 i <- j - 1
5 while i > 0 and A[i] > key
6 do temp <- A[i+1]
7 A[i+1] <- A[i]
8 A[i] <- temp
9 i <- i -1
10 A[i + 1] <- key
did I get something wrong?
please help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
插入排序中发生的不是交换。
它将大于要插入的项的每一项从当前排序部分的末尾向下移动一个索引,然后在旧值向上移动后将新记录插入到正确的位置。
What's happening in insertion sort is not a swap.
It is moving each item greater than the one you want to insert up by one index working down from the end of the currently sorted section, and then inserting the new record at the correct place after the old value is moved up.
不,事实并非如此。
该值在一开始就已保存。
它保存
j
,然后移动所有其他元素,直到找到正确的位置No it does not.
The value is already saved in the beggining.
It saves
j
and then shifts all the other elements until it finds the proper place该代码正在执行“多次交换”,更准确地说,将 ak 元素就地旋转一个位置。这需要一个辅助
key
变量,就像交换一样。The code is doing a "multi-swap", more precisely a rotation of a k elements by one position, in-place. This takes a single auxiliary
key
variable, like a swap does.我遇到同样的问题。下面是正确实现上述伪代码的 C 代码。
棘手的部分是伪代码使用基于 1 的数组表示法,这与大多数编程语言不同!
I experience the same problem. Below is the code in C which implements the above pseudo-code correctly.
The tricky part about this was that the pseudo code is using 1-based array notations unlike most programming languages!