Read twice please complete and full answer in order to give

Read twice please, complete and full answer in order to give full credit,thanks.

You are given a set of n integers. Give an O(n 2 ) algorithm to decide if there exist three numbers a, b and c in the set such that a + b = c (Hint: sort the numbers first).

Solution

void swap(int *firstElement, int *secondElement)
{
int temp = *firstElement;
*firstElement = *secondElement;
*secondElement = temp;
}

int _tmain(int argc, _TCHAR* argv[])
{
   int arrays[] = {1, 3, 4, 15, 7, 20, 27, 0, 2, 1, 2, 0};
   int n = sizeof (arrays)/sizeof arrays[0];
   for (int i = 0; i < n; i++)
   {
       for (int j = 0; j < n-i-1; j++)
       {
           if (arrays[j] > arrays[j+1])
           {
               swap(&arrays[j], &arrays[j+1]);
           }
       }
   }
   for (int i = 0; i < 12; i++)
   {
       int a = arrays[i];
       //int k = i + 1;
       for(int j = ++i; j < 12; j++)
       {
           int b = arrays[j];
           if (a + b == arrays[j + 1])
           {
               std::cout<<\"a = \"<<a<<\" b = \"<<b<<\" and c = \"<<arrays[j + 1]<<std::endl;
           }
           std::cout<<std::endl;
       }

   }
   getchar();
   return 0;
}

Read twice please, complete and full answer in order to give full credit,thanks. You are given a set of n integers. Give an O(n 2 ) algorithm to decide if there

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site