title: How does this "Lexographic order generation algorithm" work?
body: <p>from <a href="http://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order" rel="nofollow noreferrer">Wikipedia</a>:</p>
  
  <p><strong>Lexicographical order generation</strong></p>
  
  <blockquote>
    <p>For every number k, with 0 ≤ k &lt; n!,
    the following algorithm generates the
    corresponding lexicographical
    permutation of the initial sequence
    sj, j = 1, ..., n:</p>
  
  <pre><code>function permutation(k, s) {
       var int n:= length(s); factorial:= 1;
       for j= 2 to n- 1 {             // compute (n- 1)!
           factorial:= factorial* j;
       }
       for j= 1 to n- 1 {
           tempj:= (k/ factorial) mod (n+ 1- j);
           temps:= s[j+ tempj]
           for i= j+ tempj to j+ 1 step -1 {
               s[i]:= s[i- 1];      // shift the chain right
           }
           s[j]:= temps;
           factorial:= factorial/ (n- j);
       }
       return s;
   }
  </code></pre>
  </blockquote>
  
  <p>What is the <strong>logic</strong> behind this? <strong>How does it work??</strong></p>