Algorithm to apply permutation in constant memory space

后端 未结 8 1582
温柔的废话
温柔的废话 2020-12-13 21:29

I saw this question is a programming interview book, here I\'m simplifying the question.

Assume you have an array A of length n, and you ha

8条回答
  •  醉话见心
    2020-12-13 21:51

    Here a clearer version which takes a swapElements function that accepts indices, e.g., std::swap(Item[cycle], Item[P[cycle]])$ Essentially it runs through all elements and follows the cycles if they haven't been visited yet. Instead of the second check !visited[P[cycle]], we could also compare with the first element in the cycle which has been done somewhere else above.

     bool visited[n] = {0};
     for (int i = 0; i < n; i++)   {
         int cycle = i;
         while(! visited[cycle] && ! visited[P[cycle]]) {
             swapElements(cycle,P[cycle]);
             visited[cycle]=true;
             cycle = P[cycle];
         }
     }
    

提交回复
热议问题