Professional Documents
Culture Documents
CorrctionDS Review AlgoComplexity
CorrctionDS Review AlgoComplexity
CorrctionDS Review AlgoComplexity
Exercise 1
1. d) O(n^2)
2. c) O(n)
3. b) O(log n)
4. d) O(n^2)
5. c) O(n)
6. b) It represents the scenario where the algorithm performs best.
7. Write a Java program to perform Selection Sort on an array of strings in alphabetical
order. What is the complexity of this algo in the worst case and best case ?
Exercise 2
class BinaryTree {
Node root;
The time complexity of the insertion operation in a binary search tree is O(h), where h is the
height of the tree. In the worst-case scenario, when the tree is skewed (unbalanced), the height of
the tree can be equal to the number of nodes, resulting in a time complexity of O(n). However, in
a balanced binary search tree, the height is usually log(n), where n is the number of nodes,
resulting in an average time complexity of O(log n).
2. Height method code:
class BinaryTree {
Node root;
// Return the maximum of the heights of the left and right subtrees,
plus 1 for the current node
return Math.max(leftHeight, rightHeight) + 1;
}
}
java
class BinaryTree {
Node root;
// Recursively check the left and right subtrees with updated range
limits
return isBSTUtil(root.left, min, root.data - 1) &&
isBSTUtil(root.right, root.data + 1, max);
}
}