[英]STL std::sort() uses Introsort, but how does it work?
I don't really get the Introsort algorithm. 我不太了解Introsort算法。 As you can see I added the pseudocode of it. 如您所见,我添加了它的伪代码。 What is meant by the maxdepth? 最大深度是什么意思?
What does that mean " ⌊log(length(A))⌋ × 2
" 这是什么意思“ ⌊log(length(A))⌋ × 2
”
I hope someone can explain it to me. 我希望有人可以向我解释。
procedure sort(A : array):
let maxdepth = ⌊log(length(A))⌋ × 2
introsort(A, maxdepth)
procedure introsort(A, maxdepth):
n ← length(A)
p ← partition(A) // assume this function does pivot selection, p is the final position of the pivot
if n ≤ 1:
return // base case
else if maxdepth = 0:
heapsort(A)
else:
introsort(A[0:p], maxdepth - 1)
introsort(A[p+1:n], maxdepth - 1)
Re your question on ⌊log(length(A))⌋ × 2
, the ⌊...⌋
bit simply means floor
, the highest integer less than or equal to the value. 在⌊log(length(A))⌋ × 2
上⌊log(length(A))⌋ × 2
您的问题,the ⌊...⌋
位仅表示floor
,即小于或等于该值的最高整数。
In a less mathematical language, it would be int(log(length(A))) * 2
. 用较少的数学语言,它将是int(log(length(A))) * 2
。
And just in case someone brings up the difference between floor
(round toward -∞
) and int
(round toward 0
), it's irrelevant here as the length must be a non-negative integer. 万一有人提出了floor
(朝-∞
舍入)和int
(朝0
舍入)之差,这在这里是无关紧要的,因为长度必须是非负整数。 You'll still run into mathematical trouble if the length is zero but that's an exceptional case since it probably doesn't need sorting :-) 如果长度为零,您仍然会遇到数学上的麻烦,但这是一个例外情况,因为它可能不需要排序:-)
As to why maxdepth
exists, this is obviously an algorithm based on trees - the use of log
also supports this since the depth of a balanced tree tends to be proportional to the logarithm of the number of nodes in it. 至于为什么 maxdepth
存在,显然这是一种基于树的算法log
的使用也支持这一点,因为平衡树的深度往往与其中的节点数的对数成正比。
What seems to be happening is that, if the introsort gets beyond a certain depth, it just switches over to heapsort for the remainder. 似乎正在发生的事情是,如果内省型超出了某个深度,它将仅切换到堆式剩余部分。
And, just one minor note: std::sort()
is not required to use Introsort (as your title seems to imply), the standard mandates behaviour such as at most Nlog 2 N comparisons, where N=last-first
but otherwise makes no demands on algorithm choice. 而且,只是一个小小的提醒: std::sort()
不需要使用内省排序(如您的标题似乎暗示),该标准规定的行为,如at most Nlog 2 N comparisons, where N=last-first
但其他品牌无需算法选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.