Questions On Unit 1
Questions On Unit 1
Questions On Unit 1
Consider the following iterative algorithm in C++ that prints numbers from 1 to N:
void printNumbers(int N) {
for (int i = 1; i <= N; ++i) {
cout << i << " ";
}
}
What is the time complexity of the printNumbers algorithm in terms of N?
A) O(1)
B) O(N)
C) O(N^2)
D) O(log N)
2.Given the iterative algorithm below that calculates the factorial of a number in C++:
int factorial(int N) {
int result = 1;
for (int i = 1; i <= N; ++i) {
result *= i;
}
return result;
}
What is the time complexity of the factorial algorithm in terms of N?
A) O(1)
B) O(N)
C) O(N^2)
D) O(log N)
3.Consider the iterative algorithm in C++ that reverses an array in-place:
void reverseArray(int arr[], int length) {
int start = 0;
int end = length - 1;
while (start < end) {
swap(arr[start], arr[end]);
++start;
--end;
}}
What is the time complexity of the reverseArray algorithm in terms of the length of the array,
length?
A) O(1)
B) O(N)
C) O(N^2)
D) O(log N)
4.Given this iterative algorithm in C++ that performs a linear search in an array:
int linearSearch(int arr[], int length, int target) {
for (int i = 0; i < length; ++i) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
What is the time complexity of the linearSearch algorithm in terms of the length of the array,
length?
A) O(1)
B) O(N)
C) O(N^2)
D) O(log N)
5.Consider this iterative algorithm in C++ that calculates the nth Fibonacci number:
int fibonacci(int n) {
if (n < 2)
return n;
int prev = 0, curr = 1;
for (int i = 2; i <= n; ++i) {
int next = prev + curr;
prev = curr;
curr = next;
}
return curr;
}
What is the time complexity of the fibonacci algorithm in terms of n?
A) O(1)
B) O(n)
C) O(log n)
D) O(n^2)
12. In Selection Sort, what is the time complexity for the best-case scenario?
A) O(1)
B) O(n)
C) O(n log n)
D) O(n^2)
13.Selection Sort sorts the array by repeatedly selecting the:
A) Smallest element and moving it to the beginning
B) Largest element and moving it to the end
C) Middle element and moving it to the middle
D) Elements at odd positions
A) Bubble Sort
B) Selection Sort
C) Insertion Sort
D) Merge Sort
20.If an algorithm has a time complexity of O(n^2), which of the following statements is
true?
a) The algorithm has a best-case time complexity of n^2
b) The algorithm has an average-case time complexity of n^2
c) The algorithm has a worst-case time complexity of n^2
d) All of the above
21.Which notation provides both an upper and lower bound on the time complexity of an
algorithm?
a) Big O notation
b) Omega notation
c) Theta notation
d) None of the above
22.If an algorithm has a time complexity of Θ(n), what can be said about its best-case and
worst-case time complexity?
a) The best-case time complexity is Θ(n) and the worst-case time complexity is Θ(n)
b) The best-case time complexity is O(n) and the worst-case time complexity is Ω(n)
c) The best-case time complexity is Ω(n) and the worst-case time complexity is O(n)
d) None of the above