Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The algorithm can be summarrized in pseudo-code as :</p> <ol> <li>mark the current position</li> <li>go backward one character at a time until a space is found or end of input is reached</li> <li>now go forward copying each character to output, then go back to 1., except if eoi is reached</li> </ol> <p>So the input is traversed once in reverse, and one more time forward, but without coming back to a previously read position in either step 2. or 3. And when switching from step 3. to 1. it directly adjust the iterator. The <code>count</code> variable is used to track the state of the algorithm (it is in fact a simple state-machine). It is also reused to define the direction of the iteration.</p> <p>So, the algorithm is in fact <code>O(n)</code>.</p> <hr> <p>For more clarity, it could be rewritten as this, without changing the complexity:</p> <pre><code>void printStringWithWordReversed(const char* a) { int i,j,display_ToVal= strlen(a)-1, display_FromVal; for( i=display_ToVal; i&gt;=0 ; i=i+-1) { if ( (a[i] == ' ' || i == 0)) { // When entering this branch, we are switching from state 2 to // state 3 (this is the content of the first branch). cout &lt;&lt; " "; display_FromVal = i; if ( i == 0 ) cout &lt;&lt; a[i]; // This loop correspond to the state 3, and is equivalent to the // previous code in the particular case when count == 1. for (j = display_FromVal+1; j &lt;= display_ToVal; j=j+1) { cout &lt;&lt; a[j]; } // This postlude correspond to the transition from state 3 to state 1 // and correspond to the second branch in the original algorithm. display_ToVal = display_FromVal - 1; if ( i == 0 ) break; continue; } } } </code></pre> <p>So we lookup each word starting from the end and output them in correct order. This is clearly <code>O(n)</code> with both implementation (both in time and space if we assume that <code>cout</code> insertion operator for <code>char</code> is <code>O(1)</code>) since adding a <em>fixed number</em> (here two) of <code>O(n)</code> algorithm is still <code>O(n)</code> (the constant is ignored).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload