What will be the time complexity of the following code? using namespace std;…

2024

What will be the time complexity of the following code?

using namespace std;

void func(int a[], int n, int k)

{

if (k <= n)

{

for (int i = 0; i < k/2; i++)

swap(a[i], a[k-i-1]);

}

}

int main()

{

int a[] = {1, 2, 3, 4, 5};

int n = sizeof(a) / sizeof(int), k = 3;

func(a, n, k);

for (int i = 0; i < n; ++i)

cout << a[i]<<" ";

return 0;

}

  1. A.

    O(k)

  2. B.

    O(n)

  3. C.

    O(k log k)

  4. D.

    O(n log n)

Attempted by 63 students.

Show answer & explanation

Correct answer: A

Answer: a

Explanation: The given code reverses only a specified segment of the input array. This segment is decided by the value of k so the time complexity of the code will be O(k).

Explore the full course: Coding For Placement