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.
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 ofvector_B. So if there are m elements invector_Aand n elements invector_B, this will take O(mn) time to find all matches — quite slow.Suppose we sort these two vectors, and reorder
mark1andmark2accordingly as well. What you now notice is that when looking for a particular element invector_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_Aandvector_B. Let’s call theseaandbrespectively. Now only one of 3 cases can occur:a < b. In this case, we can conclude thatacannot appear anywhere invector_B, since all later elements will be at least as large asb, which is already too large.a > b. Similarly we can conclude thatbcannot appear anywhere invector_A, since all later elements will be at least as large asa, which is already too large.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.