Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What will be the complexity of this code?

My code is :

vector<int> permutation(N); 
vector<int> used(N,0);

void try(int which, int what) {
  // try taking the number "what" as the "which"-th element
  permutation[which] = what;
  used[what] = 1;

  if (which == N-1)
    outputPermutation();
  else
   // try all possibilities for the next element
  for (int next=0; next<N; next++)
    if (!used[next])
    try(which+1, next);

  used[what] = 0;
} 

int main() {
  // try all possibilities for the first element
  for (int first=0; first<N; first++)
    try(0,first);
}

I was learning complexity from some website where I came across this code. As per my understanding, the following line iterates N times. So the complexity is O(N).

for (int first=0; first<N; first++)

Next I am considering the recursive call.

for (int next=0; next<N; next++)
   if (!used[next])
    try(which+1, next);

So, this recursive call has number of step involved = t(n) = N.c + t(0).(where is some constant step) There we can say that for this step, the complexity is = O(N).

Thus the total complexity is - O(N.N) = O(N^2)

Is my understanding right? Thanks!

like image 887
Srijani Ghosh Avatar asked Oct 20 '22 05:10

Srijani Ghosh


1 Answers

Complexity of this algorithm is O(N!) (or even O(N! * N) if outputPermutation takes O(N) which seems possible).

This algorithm outputs all permutations of 0..N natural numbers without repetitions.

Recursive function try itself sequentially tries to put N elements into position which and for each try it recursively invokes itself for the next which position, until which reaches N-1. Also, for each iteration try is actually invoked (N - which) times, because on each level some element is marked as used in order to eliminate repetitions. Thus the algorithm takes N * (N - 1) * (N - 2) ... 1 steps.

like image 100
Aivean Avatar answered Oct 21 '22 23:10

Aivean