What will be the time complexity of the following code? [code] #include <bits/stdc++.h> using namespace std; void func(int arr[], int

Trang Mắm

New member
What will be the time complexity of the following code?
Code:
#include <bits/stdc++.h> 
using namespace std; 
void func(int arr[], int left, int right) 
{ 
    	while (left < right) 
	{ 
		int temp = arr[left]; 
		arr[left] = arr[right]; 
		arr[right] = temp; 
		left++; 
		right--; 
	} 
}	 
void printArray(int arr[], int size) 
{ 
    for (int i = 0; i < size; i++) 
    cout << arr[i] << " "; 
} 
int main() 
{ 
	int arr[] = {1,4,3,5}; 
	int n = sizeof(arr) / sizeof(arr[0]); 
	func(arr, 0, n-1); 
	printArray(arr, n); 
	return 0; 
}
A. O(n)
B. O(log n)
C. O(1)
D. O(n log n)
 
Answer: a
Explanation: The given code reverses the input array and then prints the resulting array. So the time complexity of the given code will linearly vary with the number of elements in the array and thus the time complexity will be O(n).
 

Tìm kiếm

Back
Top