What is the worst case time complexity of inserting n elements into an empty linked list, if the linked list needs to be maintained in sorted order ?
(B) Θ(n log n)
Explanation: This question is ambiguous: “needs to be maintained in sorted order”, there are two possible cases:
- Needs to be maintained in sorted order on each step (after each insertion).
When we are inserting an element in to empty linked list and to perform sorted order list of every element will take O(n2).
Each Insertion into a sorted linked list will take θ(n) and hence the total cost for n operations is θ(n2).
- Needs to be maintained in sorted order on final step (only after all insertion).
When we are inserting all elements into an empty linked list and to perform a sorted list (using merge sort) after inserting all elements will take O(n log n) time.
Official answer by GATE is Θ(n2).
Quiz of this Question