处理快速排序中的重复键
简单的快速排序将花费 O(n^2) 时间对不包含唯一键的数组进行排序,因为所有键都将在主值之前或之后进行分区。有多种方法可以处理重复的键(如 快速排序是最佳的)。建议的解决方案仅适用于 Hoare 分区,但我已经实现了 Lomuto 分区。为了处理重复的键,我交替将重复项移动到枢轴的左侧和将重复项移动到枢轴的右侧。该算法的工作原理如下:
//partition array from index start to end
select pivot element and move it to array[start]
boolean dupHandler=true;
int index=start;
for(i from start+1 to end)
int val=array[start].compareTo(array[i]);
if(val==0)
if(dupHandler)
swap array[++index] and array[i]
dupHandler=!dupHandler;
else if(val>0)
swap array[++index] and array[i]
swap array[start] and array[index]
是否有更好(更有效)的方法来处理重复键?
编辑:我的代码(如图所示)要求compareTo与equals一致(即使认为这不是要求)
A naïve quicksort will take O(n^2) time to sort an array containing no unique keys, because all keys will be partitioned either before or after the pivot value. There are ways to handle duplicate keys (like one described in Quicksort is Optimal). The proposed solution only works for the Hoare partition, but I've implemented the Lomuto partition. To deal with duplicate keys, I alternated between moving duplicates to the left of the pivot and moving duplicates to the right of the pivot. The algorithm works something like this:
//partition array from index start to end
select pivot element and move it to array[start]
boolean dupHandler=true;
int index=start;
for(i from start+1 to end)
int val=array[start].compareTo(array[i]);
if(val==0)
if(dupHandler)
swap array[++index] and array[i]
dupHandler=!dupHandler;
else if(val>0)
swap array[++index] and array[i]
swap array[start] and array[index]
Is there a better (more efficient) way to handle duplicate keys?
EDIT: My code (as shown) requires compareTo to be consistent with equals (even thought that's not a requirement)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论