快速排序:为什么将枢轴移到最后?
首先将所选主元元素移动到数组末尾的动机是什么? 我唯一能看到的是,当增加较低的索引 i 时,我们不需要检查 i < n 但只有 a[i] <枢。
是这样吗?
塔克斯
·安迪
Whats the motivation of first moving the chosen pivot element to the end of the array?
The only thing I can see is that when incrementing the lower index i , we dont need to check i < n but only a[i] < pivot.
Is that it?
Thakns
Andy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
枢轴被移动到数组的末尾,因为在移动其他元素之前它不知道它会在哪里结束。为了避免在每次比较后不断移动整个数组的元素,将枢轴放置在末尾,直到数组的其余部分排序(对于快速排序的该步骤),然后放置在正确的位置。这意味着数组只需要移动两次(一次在开始,一次在结束),而不是在每次比较之后。
The pivot is moved to the end of the array because it doesn't know where it will end up until the other elements are moved. In order to avoid constantly shifting the entire array's elements after each comparison, the pivot is placed at the end until the rest of the array is sorted (for that step of the quicksort), then placed in its correct location. This means the array only needs to be shifted twice (once in the beginning, once at the end), instead of after each comparison.