What is the time complexity of the following code? int* a = new int[N]; int* b =
ID: 3554238 • Letter: W
Question
What is the time complexity of the following code? int* a = new int[N]; int* b = new int[N]; // Assume the following two lines initialize the arrays //in O(N) time. initialize(a, N); initialize(b, N); long sum = 0; for(int i=0; i < N; i++){ for(int j=0; j < N; j++){ sum += a[i]*b[j]; }}
Determine the time complexity of the following code, assuming N = vec.size(). template <typename T> void reverseVector(vector<T>& vec, int start, int end){ if(start < end){ char temp = vec[start]; vec[start] = vec[end]; vec[end] = temp; reverseVector(vec, start + 1, end What is the time complexity of the following code? int* a = new int[N]; int* b = new int[N]; // Assume the following two lines initialize the arrays //in O(N) time. initialize(a, N); initialize(b, N); long sum = 0; for(int i=0; i < N; i++){ for(int j=0; j < N; j++){ sum += a[i]*b[j]; }
}
Determine the time complexity of the following code, assuming N = vec.size(). template <typename T> void reverseVector(vector<T>& vec, int start, int end){ if(start < end){ char temp = vec[start]; vec[start] = vec[end]; vec[end] = temp; reverseVector(vec, start + 1, end Determine the time complexity of the following code, assuming N = vec.size(). template <typename T> void reverseVector(vector<T>& vec, int start, int end){ if(start < end){ char temp = vec[start]; vec[start] = vec[end]; vec[end] = temp; reverseVector(vec, start + 1, end
Explanation / Answer
1. TC =O(N^2)
because first for loop is runing N times and second for loop is also runing N times so total TC is n^2
int* a = new int[N];
int* b = new int[N];
// Assume the following two lines
initialize the arrays
//in O(N) time.
initialize(a, N);
initialize(b, N);
long sum = 0;
for(int i=0; i < N; i++){
for(int j=0; j < N; j++){
sum += a[i]*b[j];
}
}
2.
TC is O(N) because function will run size of vector which is N so time complexity is O(N)
Determine the time complexity of the following code, assuming N = vec.size().
template <typename T>
void reverseVector(vector<T>& vec, int start, int end){
if(start < end){
char temp = vec[start];
vec[start] = vec[end];
vec[end] = temp;
reverseVector(vec, start + 1, end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.