Heap's algorithm: Difference between revisions

Content deleted Content added
BattyBot (talk | contribs)
m removed Template:Multiple issues & general fixes using AWB (9866)
Bladeor (talk | contribs)
m added 'the'
Tag: gettingstarted edit
Line 3:
'''Heap's algorithm''' is an [[algorithm]] for generating [[permutation]]s. It was first proposed by B. R. Heap in 1963.<ref>{{cite journal|last=Heap|first=B. R.|title=Permutations by Interchanges|journal=The Computer Journal|year=1963|volume=6|issue=3|pages=293–4|url=http://comjnl.oxfordjournals.org/content/6/3/293.full.pdf}}</ref> It interchanges positions of elements to generate the next permutation. In a 1977 review of permutation-generating algorithms, [[Robert Sedgewick (computer scientist)|Robert Sedgewick]] concluded that it was in practical terms the fastest algorithm for then-current computers.<ref>{{cite doi|10.1145/356689.356692}}</ref>
 
== Details of the algorithm ==
Suppose we have a sequence of different characters with a length of&nbsp;''N''. Heap found that we can simply interchange the positions of two elements to get a new permutation output. Let us describe it in a recursive way. If we have got (''N''&nbsp;&minus;&nbsp;1)<nowiki>!</nowiki> permutation outputs, fixing the last element. Then if ''N'' is odd, we can switch the first element and the last one, while ''N'' is even we can switch the ''i''th (''i'' is the step number of the cycle, and now it is 1) element and the last one, then we will continue outputting the (''N''&nbsp;&minus;&nbsp;1)<nowiki>!</nowiki> permutation outputs and switching step for another ''N''&nbsp;&minus;&nbsp;1 times(''N'' times int total). The following pseudocode outputs permutations of a data array of length&nbsp;''N''.