devan
devan

Reputation: 1653

Optimal way to combine two vectors in vc++

I am finding a better logic to combine 2 vectors.

vector_A[id][mark1];
vector_B[id][mark2];

vector_A: id = [300 , 502, 401 , 900 , 800 ,700 , 250 , 001] 
          mark1 = [55 , 50 , 30 , 28 , 25 , 11 , 04 , 03]

vector_B: id = [800 , 005 , 502 , 925 ,025 ,300 , 52] 
          mark2 = [75, 60 , 50 ,35 , 30 , 25 , 04]

combination rule is If same id find in two vectors add mark1 and mark2. If not just display.

vector_combined: id = [800 , 300 , 502 , 005 , 925 , 401] 
                 mark_combine = [100, 80 , 100 , 60 , 35 ,30]

Please help me with a optimal solution.

Upvotes: 0

Views: 109

Answers (2)

j_random_hacker
j_random_hacker

Reputation: 51226

Here on SO we're happy to assist people with hints for homework questions, provided they have been up-front about acknowledging the question as homework -- as you have been :)

As things are now, to find a match for a particular element in vector_A, you need to scan every element of vector_B. So if there are m elements in vector_A and n elements in vector_B, this will take O(mn) time to find all matches -- quite slow.

Suppose we sort these two vectors, and reorder mark1 and mark2 accordingly as well. What you now notice is that when looking for a particular element in vector_B, you can stop as soon as you get to an element that is too large -- since you know that all later elements must be even larger. That will save some time.

In fact you can go one step further and look at just the 1st element of vector_A and vector_B. Let's call these a and b respectively. Now only one of 3 cases can occur:

  1. a < b. In this case, we can conclude that a cannot appear anywhere in vector_B, since all later elements will be at least as large as b, which is already too large.
  2. a > b. Similarly we can conclude that b cannot appear anywhere in vector_A, since all later elements will be at least as large as a, which is already too large.
  3. a = b. In that case, clearly this number appears in both vectors!

Bearing in mind that sorting takes just O(nlog n) time, this should give you a big hint for a faster algorithm. If you need a bit more help understanding, leave a comment.

Upvotes: 1

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132994

I am not sure if I understand your problem correctly... but, are you by any chance looking for std::set_intersection ?

The algorithm requires your ranges to be sorted. So, sort them and feed them to set_intersection

Upvotes: 1

Related Questions