@@ -54,8 +54,13 @@ Example: for n = 1,000,000, log₂(n) ≈ 20. So about 20 comparisons instead of
5454** Good: binary search (sorted array)**
5555
5656``` typescript
57- // NOTE: Each step halves the range; at most ~log₂(n) iterations.
58- // → O(log n).
57+ /**
58+ * Binary search on sorted array.
59+ * @description Halves range each step, at most log₂(n) iterations.
60+ * @param arr - Sorted array to search
61+ * @param target - Value to find
62+ * @returns Index of target or -1
63+ */
5964function binarySearch(arr : number [], target : number ): number {
6065 let left = 0
6166 let right = arr .length - 1
@@ -77,8 +82,13 @@ function binarySearch(arr: number[], target: number): number {
7782** Good: balanced BST lookup.** Same idea: each step goes left or right, so you follow one path of length O(log n).
7883
7984``` typescript
80- // NOTE: One path from root to leaf; tree height O(log n) when balanced.
81- // → O(log n).
85+ /**
86+ * Lookup key in balanced BST.
87+ * @description One path from root to leaf, height is O(log n).
88+ * @param node - Root node of BST
89+ * @param key - Key to search for
90+ * @returns Matching node or null
91+ */
8292function bstLookup(node : BSTNode | null , key : number ): BSTNode | null {
8393 if (node === null || node .key === key ) {
8494 return node
@@ -93,8 +103,13 @@ function bstLookup(node: BSTNode | null, key: number): BSTNode | null {
93103** Bad:** linear search on a sorted array (O(n)). Same input as binary search, but we scan one by one instead of halving.
94104
95105``` typescript
96- // NOTE: Scans every element until found - O(n).
97- // Use binary search when sorted.
106+ /**
107+ * Linear search on sorted array.
108+ * @description Scans every element until found, O(n) time.
109+ * @param arr - Array to search (should be sorted)
110+ * @param target - Value to find
111+ * @returns Index of target or -1
112+ */
98113function linearSearchSorted(arr : number [], target : number ): number {
99114 for (let i = 0 ; i < arr .length ; i ++ ) {
100115 if (arr [i ] === target ) {
0 commit comments