This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: Discussion 2C Notes (Week 10, March 11) TA: Brian Choi ([email protected]) Section Webpage: http://www.cs.ucla.edu/~schoi/cs32 Final Practice Problems Note: The work space provided for each problem may not be sufficient. Use scratch papers if needed. [BigO] 1. Suppose there is an array of N (~ 10,000) elements in a random order. You want to run a search and look for a certain item. Using what you have learned in this course, what is the best you can do if: (a) you run a search once? (“Is there 5 in the array?”) (b) you run a search 10,000 times? (“Is there 5? 16? 73? ...”) You may place this data in a secondary data like and/or rearrange the data to solve the problem. Support your argument using BigO. 2. Consider two vector<int> ’s x and y , each having N distinct integers. We want to merge x and y to create a third vector z , such that z has all integers that x and y have. Like x and y , z should not have any duplicate numbers. We are not concerned about keeping the elements in x , y , or z in any certain order. Here is one algorithm: void merge(const vector<int>& x, const vector<int>& y, vector<int>& z) { z.clear(); z.reserve(x.size() + y.size()); for (int i = 0; i < x.size(); ++i) z.push_back(x[i]); for (int j = 0; j < y.size(); ++j) { bool duplicate = false; for (int i = 0; i < x.size(); ++i) { if (y[j] == x[i]) { duplicate = true; break; } } if (!duplicate) z.push_back(y[j]); } } (a) What is the complexity of this algorithm? CS32: Introduction to Computer Science II Winter 2011 Copyright 2011 Brian Choi Week 10, Page 1/9 (b) Here is a different implementation of merge . What is its complexity? void merge(const vector<int>& x, const vector<int>& y, vector<int>& z) { z.clear(); z.reserve(x.size() + y.size()); for (int i = 0; i < x.size(); i++) z.push_back(x[i]); for (int j = 0; j < y.size(); j++) z.push_back(y[j]); sort(z.begin(), z.end()); int last = 0; for (int k = 1; k < z.size(); k++) { if (z[last] != z[k]) { last++; z[last] = z[k]; } } z.resize(last + 1); } (c) Which one performs better, (a) or (b)? (d) (Openended question) Is there any algorithm for merge that performs better than the version in (b)? CS32: Introduction to Computer Science II Winter 2011 Copyright 2011 Brian Choi Week 10, Page 2/9 [Trees] 3. Write nodeCount , a recursive function that counts the number of nodes in a tree rooted at node . This is a general tree, where a node can have a variable number of children. Use the following Node structure....
View
Full Document
 Spring '11
 Smallberg
 hash function, Computer Science II, Brian Choi, closest common ancestor

Click to edit the document details