1

I'm studying time complexity of recursive algorithms and I want to know the complexity of the Heap's algorithm that generate all possible permutations of n objects.

procedure generate(k : integer, A : array of any):
    if k = 1 then
        output(A)
    else
        // Generate permutations with kth unaltered
        // Initially k == length(A)
        generate(k - 1, A)

        // Generate permutations for kth swapped with each k-1 initial
        for i := 0; i < k-1; i += 1 do
            // Swap choice dependent on parity of k (even or odd)
            if k is even then
                swap(A[i], A[k-1]) // zero-indexed, the kth is at k-1
            else
                swap(A[0], A[k-1])
            end if
            generate(k - 1, A)

        end for
    end if

I think the time complexity of this is O(n * n!) but I'm not sure. All the help would be appreciated. Thank you.

trincot
  • 317,000
  • 35
  • 244
  • 286
Garais16
  • 43
  • 4
  • I think it is `O(n * (1 + n)!)`, assuming that `output(A)` takes `O(n)` time. – Nico Schertler Dec 03 '19 at 03:37
  • There are n! permutations, and each permutation requires n steps. So that's O(n * n!). See also https://en.wikipedia.org/wiki/Heap%27s_algorithm – Jim Mischel Dec 03 '19 at 05:50
  • the question is why do you need a heap? Heap is best used for quickly finding min/max for a stream of object. You do not need heap if the permutation is the goal. Which will take n! time to output – Ke Zhu Dec 03 '19 at 05:59
  • 2
    @Ke Zhu Question talks about permutation algorithm [developed by B. R. Heap](https://en.wikipedia.org/wiki/Heap's_algorithm), not about heap data structure – MBo Dec 03 '19 at 07:41

0 Answers0