Given an integer array of size , 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
View worked solution
Answer: A
To determine if an array of size is sorted in either ascending or descending order, any algorithm must verify the relationship between all adjacent elements in the worst case.
Worst-Case Analysis:
- The worst-case scenario occurs when the array is indeed fully sorted (either ascending or descending), or when the sorting order is violated only at the very last pair of elements.
- In such cases, the algorithm must scan the entire array and perform comparisons for all adjacent pairs.
- For an array of size , there are exactly adjacent pairs: .
- Thus, the algorithm performs exactly comparisons in the worst case.
Since the number of operations in the worst case is proportional to , the worst-case time complexity is .
By the definitions of asymptotic notations:
Therefore, the worst-case time complexity is both and .
Free practice · Your answers on this page are not saved.
