Difference between revisions of "TADM2E 4.8"

From Algorithm Wiki
Jump to: navigation, search
(Recovering wiki)
 
(Recovering wiki)
Line 1: Line 1:
 
(a):  
 
(a):  
<pre>
+
<pre>
 
Sort S with any nlogn sorting method of your choice.
 
Sort S with any nlogn sorting method of your choice.
for( int i = 1; i &lt;= n; ++i )
+
for( int i = 1; i <= n; ++i )
 
{
 
{
 
     int j = x - S[i];
 
     int j = x - S[i];
 
     Binary search for j in the sub-array of S[i+1~n] and close the problem once it's been found;
 
     Binary search for j in the sub-array of S[i+1~n] and close the problem once it's been found;
 
}
 
}
&lt;/pre&gt;
+
</pre>
 
(b):
 
(b):
&lt;pre&gt;
+
<pre>
 
Subtract each of S[1~n] from x to get a new array of real numbers T[1~n].
 
Subtract each of S[1~n] from x to get a new array of real numbers T[1~n].
 
int i = 1, j = 1;
 
int i = 1, j = 1;
while( i &lt;=n &amp;&amp; j &lt;= n )
+
while( i <=n && j <= n )
 
{
 
{
 
     if( S[i] == T[j] )
 
     if( S[i] == T[j] )
Line 21: Line 21:
 
     else
 
     else
 
     {
 
     {
         S[i] &lt; T[j] ? ++i : ++j;
+
         S[i] < T[j] ? ++i : ++j;
 
     }
 
     }
 
}
 
}
&lt;/pre&gt;
+
</pre>
  
 
Another Solution to part B without creating the additional Array..
 
Another Solution to part B without creating the additional Array..
&lt;pre&gt;
+
<pre>
 
i = 0;
 
i = 0;
 
j = n - 1;
 
j = n - 1;
  
for (i = 0; i &lt; j; i++)
+
for (i = 0; i < j; i++)
 
{
 
{
   while( (i &lt; j) &amp;&amp; (S[j] + S[i] &gt; x )
+
   while( (i < j) && (S[j] + S[i] > x )
 
   { j--;
 
   { j--;
 
   }
 
   }
Line 43: Line 43:
 
}
 
}
  
&quot;i&quot; scans from left to right, &quot;j&quot; from right to left,
+
"i" scans from left to right, "j" from right to left,
 
looking for the right pair...
 
looking for the right pair...
&lt;/pre&gt;
+
</pre>

Revision as of 18:23, 11 September 2014

(a):

Sort S with any nlogn sorting method of your choice.
for( int i = 1; i <= n; ++i )
{
    int j = x - S[i];
    Binary search for j in the sub-array of S[i+1~n] and close the problem once it's been found;
}

(b):

Subtract each of S[1~n] from x to get a new array of real numbers T[1~n].
int i = 1, j = 1;
while( i <=n && j <= n )
{
    if( S[i] == T[j] )
    {
        problem solved;
        break;
    }
    else
    {
        S[i] < T[j] ? ++i : ++j;
    }
}

Another Solution to part B without creating the additional Array..

i = 0;
j = n - 1;

for (i = 0; i < j; i++)
{
  while( (i < j) && (S[j] + S[i] > x )
  { j--;
  }
  if (x == (S[j] + S[i])
  {
    return (S[i],S[j]);
    break;
  }
}

"i" scans from left to right, "j" from right to left,
looking for the right pair...