Sunday, 23 October 2016

CLRS: 2.3-7*

★ Describe a Θ(nlgn)-time algorithm that, given a set S of n integers and another integer x, determines whether or not there exists two elements of S whose sum is exactly x.

#include<iostream>
#include<algorithm>
#include<vector>
#include<iterator>

using namespace std;

int main(){
    vector<int>v = {2,1,4,5,8,9,2,6};
    int number,j=1;
    cout<<"Enter the Number";
    cin>>number;
    sort(v.begin(),v.end());
    for(auto &i:v){
        if (binary_search(v.begin()+j, v.end(), (number-i))){
            cout<<"Found The two numbers whose sum is exactly equal to"<<number<<endl
                <<i<<" and "<<number-i;
            break;
        }
        ++j;
    }
    return 0;
}

 There is something special about this post. That special thing is the variable j . Try to run the code by omitting the variable j and taking number = 2 . You will get surprising results! Not surprising results, I would rather call it subtly wrong error.  If you find the post to be interesting, Please do write your review in the comments down below. For regular updates Subscribe to the Blog.

No comments:

Post a Comment