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

Như Quỳnh

New member
What will be the time complexity of the following code?
Code:
#include <bits/stdc++.h> 
using namespace std; 
void func1(int arr[], int n) 
{ 
	int k = arr[0], i; 
	for (i = 0; i < n - 1; i++) 
		arr[i] = arr[i + 1]; 
	arr[i] = k; 
} 
void func(int arr[], int d, int n) 
{ 
	for (int i = 0; i < d; i++) 
		func1(arr, n); 
} 
void printArray(int arr[], int n) 
{ 
	for (int i = 0; i < n; i++) 
		cout << arr[i] << " "; 
} 
int main() 
{ 
	int arr[] = { 1, 2, 3, 4, 5}; 
	int n = sizeof(arr) / sizeof(arr[0]); 
    int d = 3;
	func(arr, d, n); 
	printArray(arr, n); 
	return 0; 
}
A. O(n*d)
B. O(n)
C. O(d)
D. O(n$^{2}$)
 
Answer: a
Explanation: The given code rotates the input array by d. It does so by rotating the elements one by one until the desired rotation is achieved. Each element takes O(n) time for rotation and there are d such elements in the array. So the time complexity would be O(n*d).
 

Tìm kiếm

Back
Top