1

I am trying to understand how the Heap's algorithm for permutations works but I find it very hard to understand. I haven't found an example of recursion tree to explain how the code works. Can anyone provide one for me?

Let's say I want to compute all permutations of the list [1,2,3,4] in python. I know how to implement the algorithm in python,

def heapPermutation(a, size):
    if size == 1:
        return
    for i in range(size):
        heapPermutation(a,size-1)
            
        if size % 2 == 0:
            a[i],a[size-1] = a[size-1],a[i]
        else:
            a[0],a[size-1] = a[size-1],a[0]

but still I get confused by the recursive calls.

11
  • This is a particularly tricky question, since your function here takes advantage of both recursivity and the mutability of the argument a. Maybe using a visual debugger to follow along would help you find out how all of this works ? Commented Mar 9, 2022 at 23:18
  • 2
    That's not a correct implementation of Heap's Algorithm, even if you correct the typo in for i in range(2):. (I see that the Wikipedia page on Heap's algorithm has been defaced again. Sigh.) Commented Mar 9, 2022 at 23:52
  • @rici ops, let me correct the typo Commented Mar 10, 2022 at 0:47
  • 1
    Cool. But it's still not the correct implementation. Sadly, that particular incorrect implementation is very widespread. See stackoverflow.com/a/29044942/1566221 Commented Mar 10, 2022 at 1:05
  • @rici Doing some searching, Sedgewick now has his original 1977 paper with Heap's algorithm free on his website. Might be useful to OP here, and/or if you want to add that reference to your great answer in the other thread. Commented Mar 10, 2022 at 1:10

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.