1+ import content from './text/binary-search-fundamentals-content.md?raw' ;
2+ import example from './text/binary-search-fundamentals-example.js?raw' ;
3+ import completed from './text/binary-search-fundamentals-completed.js?raw' ;
4+
15export const binarySearchFundamentalsChapter = {
26 id : 'binary-search-fundamentals' ,
37 title : 'Binary Search Fundamentals' ,
48 sectionId : 'sorting-and-binary-search' ,
59 previousChapterId : 'sort-method' ,
6- content : `## Binary Search Fundamentals
7-
8- Binary search is a highly efficient algorithm for finding an element in a sorted array. It works by repeatedly dividing the search interval in half, making it significantly faster than linear search for large datasets.
9-
10- TBD
11-
12- ## The Binary Search Algorithm
13-
14- Binary search follows a divide-and-conquer approach:
15-
16- 1. Start with the middle element of the sorted array
17- 2. If the target value equals the middle element, return the index
18- 3. If the target value is less than the middle element, search the left half
19- 4. If the target value is greater than the middle element, search the right half
20- 5. Repeat until the element is found or the search interval is empty
21-
22- TBD
23-
24- ## Basic Implementation
25-
26- Here's a straightforward implementation of binary search:
27-
28- \`\`\`javascript
29- function binarySearch(arr, target) {
30- let left = 0;
31- let right = arr.length - 1;
32-
33- while (left <= right) {
34- // Calculate middle index (avoiding integer overflow)
35- const mid = Math.floor(left + (right - left) / 2);
36-
37- // Check if target is present at mid
38- if (arr[mid] === target) {
39- return mid;
40- }
41-
42- // If target is greater, ignore left half
43- if (arr[mid] < target) {
44- left = mid + 1;
45- }
46- // If target is smaller, ignore right half
47- else {
48- right = mid - 1;
49- }
50- }
51-
52- // Target not found
53- return -1;
54- }
55-
56- // Example usage
57- const sortedArray = [1, 3, 5, 7, 9, 11, 13, 15, 17];
58- console.log(binarySearch(sortedArray, 7)); // Output: 3
59- console.log(binarySearch(sortedArray, 6)); // Output: -1
60- \`\`\`
61-
62- TBD
63-
64- ## Time and Space Complexity
65-
66- Binary search has excellent performance characteristics:
67-
68- - **Time Complexity**: O(log n)
69- - Each step eliminates half of the remaining elements
70- - For an array of 1 million elements, binary search takes at most 20 comparisons
71-
72- - **Space Complexity**:
73- - Iterative: O(1) - uses constant extra space
74-
75- TBD
76-
77- ## Comparison with Linear Search
78-
79- To appreciate binary search, let's compare it with linear search:
80-
81- \`\`\`javascript
82- function linearSearch(arr, target) {
83- for (let i = 0; i < arr.length; i++) {
84- if (arr[i] === target) {
85- return i;
86- }
87- }
88- return -1;
89- }
90- \`\`\`
91-
92- | Array Size | Linear Search (worst case) | Binary Search (worst case) |
93- |------------|----------------------------|----------------------------|
94- | 10 | 10 comparisons | 4 comparisons |
95- | 100 | 100 comparisons | 7 comparisons |
96- | 1,000 | 1,000 comparisons | 10 comparisons |
97- | 1,000,000 | 1,000,000 comparisons | 20 comparisons |
98- | 1 billion | 1 billion comparisons | 30 comparisons |
99-
100- TBD
101-
102- ## Prerequisites for Binary Search
103-
104- Binary search requires:
105-
106- 1. **Sorted Data**: The array must be sorted for binary search to work
107- 2. **Random Access**: The data structure must support efficient random access (O(1) time)
108-
109- This means binary search works well with:
110- - Arrays
111- - Array-like data structures with O(1) access by index
112-
113- But not with:
114- - Linked lists (no efficient random access)
115- - Unsorted collections
116-
117- TBD
118-
119- ## Common Pitfalls and Edge Cases
120-
121- When implementing binary search, watch out for:
122-
123- ### 1. Integer Overflow
124-
125- In some languages, calculating the middle index as \`(left + right) / 2\` can cause integer overflow. Use \`left + (right - left) / 2\` instead.
126-
127- ### 2. Infinite Loops
128-
129- Ensure your termination condition and index updates are correct to avoid infinite loops.
130-
131- ### 3. Off-by-One Errors
132-
133- Be careful with the boundary conditions (left <= right vs. left < right).
134-
135- ### 4. Empty Arrays
136-
137- Handle empty arrays appropriately.
138-
139- ### 5. Duplicate Elements
140-
141- Standard binary search finds any matching element, not necessarily the first or last occurrence.
142-
143- TBD
144-
145- ## Binary Search in JavaScript
146-
147- JavaScript doesn't have a built-in binary search method, but you can use the implementations shown above. For sorted arrays, you can also use:
148-
149- \`\`\`javascript
150- // Find the insertion point for target in a sorted array
151- function findInsertionPoint(arr, target) {
152- let left = 0;
153- let right = arr.length;
154-
155- while (left < right) {
156- const mid = Math.floor(left + (right - left) / 2);
157-
158- if (arr[mid] < target) {
159- left = mid + 1;
160- } else {
161- right = mid;
10+ content : content ,
11+ exercise : {
12+ starterCode : example ,
13+ solution : completed ,
14+ question : `
15+ # Exercise Question
16+ ` ,
17+ solution_explanation : `
18+ # Solution Explanation
19+ it goes like this
20+ `
16221 }
163- }
164-
165- return left;
166- }
167-
168- // Check if element exists using the insertion point
169- function includes(arr, target) {
170- const index = findInsertionPoint(arr, target);
171- return index < arr.length && arr[index] === target;
172- }
173- \`\`\`
174-
175- TBD
176-
177- ## Real-World Applications
178-
179- Binary search is used in many practical applications:
180-
181- 1. **Database Indexing**: Finding records in sorted indexes
182- 2. **Dictionary Lookups**: Finding words in a dictionary
183- 3. **Debugging**: Finding the first occurrence of a bug in a version control history
184- 4. **Machine Learning**: Finding optimal hyperparameters
185- 5. **Computer Graphics**: Intersection detection in ray tracing
186- 6. **Network Routing**: Finding the best route in a routing table
187-
188- TBD
189-
190- ## Beyond Basic Binary Search
191-
192- Binary search can be extended to solve more complex problems:
193-
194- 1. **Finding the first or last occurrence** of an element in a sorted array with duplicates
195- 2. **Finding the closest element** to a target value
196- 3. **Searching in rotated sorted arrays**
197- 4. **Finding the peak element** in a bitonic array
198- 5. **Binary search on answer space** for optimization problems
199-
200- We'll explore these variants in the next chapter.
201-
202- TBD` ,
203- exercise : null
20422} ;
0 commit comments