Skip to main content

GATE CSE 2024Algorithms › Growth of Functions & Complexity AnalysisVerified

GATE CSE 2024 PYQ: Given an integer array of size N N N , we want to check if the array is sorted (in either ascending or…

Given an integer array of size NN, we want to check if the array is sorted (in either ascending or descending order). An algorithm solves this problem by making a single pass through the array and comparing each element of the array only with its adjacent elements. The worst-case time complexity of this algorithm is

  1. A
    both O(N)\mathrm{O}(N) and Ω(N)\Omega(N)
    Correct answer
  2. B
    O(N)\mathrm{O}(N) but not⁡Ω(N)\operatorname{not} \Omega(N)
  3. C
    Ω(N)\Omega(N) but not O(N)\mathrm{O}(N)
  4. D
    neither O(N)\mathrm{O}(N) nor Ω(N)\Omega(N)

Answer

(A) both O ( N ) \mathrm{O}(N) O ( N ) and Ω ( N ) \Omega(N) Ω ( N )

Approach

The algorithm is a single scan comparing adjacent elements. The worst case is when the scan cannot stop early, i.e. the array is already sorted or the only inversion is near the very end. Then it must perform about $N-1$ comparisons. This makes the worst-case running time $\Theta(N)$, which is equivalent to both $O(N)$ and $\Omega(N)$ being true.

The algorithm makes one linear pass and compares adjacent elements. In the worst case it must inspect essentially all adjacent pairs, giving $T_{\text{worst}}(N)=\Theta(N)$. A function that is $\Theta(N)$ is simultaneously $O(N)$ and $\Omega(N)$, so option A is correct.

Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.