Given sum

Design an algorithm to find all pairs of integers within an array which sum to a specified value.

C++:
01 int compare (const void * a, const void * b)
02 {
03   return ( *(int*)a *(int*)b );
04 }
05 
06 bool givenSum(int *A, int size, int& x, int& y, int sum)
07 {
08     int *B=new int[size];
09     for(int i=0;i<size;i++)
10         B[i]=A[i];
11     qsort(B,size,sizeof(int),compare);
12     int a=0;
13     int b=size1;
14     while(a<b){
15         if((B[a]+B[b])==sum){
16             x=B[a];
17             y=B[b];
18             return true;
19         }
20         if((B[a]+B[b])<sum)
21             a++;
22         else
23             b;
24     }
25     return false;
26 }
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s