Algorithm 246: Graycode
暂无分享,去创建一个
p r o c e d u r e TREESORT 3 (M, n) ; v a l u e n; a r r a y M; i n t e g e r n; c o m m e n t TREESORT 3 is a major revision of TREESORT [R. W. Floyd, Alg. 113, Comm. A C M 5 (Aug. 1962), 434] suggested by H E A P S O R T [J. W. J. Williams, Alg. 232, Comm. A CM 7 (June 1964), 347] from which it differs in being an in-place sort. I t is shor ter and probably faster, requir ing fewer comparisons and only one division. I t sorts the ar ray M[1 :n], requir ing no more t han 2 X ( 2 ~ ' p 2 ) X (pl ) , or approximate ly 2 X n X ( log2(n ) l ) comparisons and half as many exchanges in the worst case to sort n = 2 Tp 1 items. The a lgor i thm is most easily followed if M is t hough t of as a tree, wi th M[j+2] the fa ther of M[j] for 1 < j ~ n; b e g i n p r o c e d u r e exchange (x,y); real x,y; b e g i n r e a l t; t := x; x := y; y := t e n d exchange; p r o c e d u r e siftup (i ,n); v a l u e i, n; i n t e g e r i, n; c o m m e n t M[i] is moved upward in the subtree of M[l :n] of which it is the root ; b e g i n r ea l copy; i n t e g e r j ; copy := M[i]; loop: j := 2 X i ; i f j =< n t h e n b e g i n i f j < n t h e n b e g i n i f M [ j + i ] > M[j] t h e n j := j + 1 e n d ; i f M[j] > copy t h e n b e g i n M[i] := M[j]; i := j ; go to loop e n d e n d ; M[i] := copy e n d siftup; i n t e g e r i ; fo r i := n ÷ 2 s t e p --1 u n t i l 2 do siftup (i ,n); for i := n s t e p --1 u n t i l 2 do b e g i n siftup (1,i) ; c o m m e n t M[j+2] ~ M[j] for 1 < j ~ i ; exchange (M[1], M[i]); c o m m e n t M[i:n] is fully sor ted; e n d e n d TREESORT 3