Hi, I have a function that I need to find the Big O of, and have already written my notes down, but am not sure whether or not my answer is correct.
So what I've deduced from the code below is the following:
1. Vector creation is... constant (?)
2. The first two loops = 2N
3. Sort is said to use NlogN, so I'll use that.
4. While loop does things up to N-1 times if I recall correctly, so that = N
5. For loop has insertBefore, which could have either logN, N, or NlogN...
6. I know that the last for loop is = N, but I'm stuck with insertBefore
7. insertBefore seems to work up to N-1 in its worst case scenario, which means my guess is that it is O(N)?
Adding them all together, I get O(N^2), but I am not 100% sure about this.
Can someone assist me with this? Thank you
The code can be found below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
void Set::unite(const Set& set1, const Set& set2)
{
vector<ItemType> v;
for (Node* p1 = set1.m_head->m_next; p1 != set1.m_head; p1 = p1->m_next)
v.push_back(p1->m_value);
for (Node* p2 = set2.m_head->m_next; p2 != set2.m_head; p2 = p2->m_next)
v.push_back(p2->m_value);
// sorted using O(N log N)
sort(v.begin(), v.end());
while (m_head->next != m_head)
doErase(m_head->m_next);
for (size_t k = 0; k < v.size(); k++)
{
if (k == 0 || v[k] != v[k-1])
insertBefore(m_head, v[k]);
}
}
|