1+ /**
2+ * A generator function that performs Binary Search and yields visualization steps.
3+ * @param {number[] } array - The array to search through (must be sorted).
4+ * @param {number } target - The value to find.
5+ * @yields {{lowIndex: number, highIndex: number, midIndex: number | null, foundIndex: number | null, message?: string}}
6+ */
7+ export function * binarySearch ( array , target ) {
8+ const targetNumber = parseInt ( target ) ;
9+ let low = 0 ;
10+ let high = array . length - 1 ;
11+ let foundIndex = null ;
12+
13+ // Initial state: show the full search range
14+ yield { lowIndex : low , highIndex : high , midIndex : null , foundIndex : null } ;
15+
16+ while ( low <= high ) {
17+ let mid = Math . floor ( ( low + high ) / 2 ) ;
18+
19+ // Step 1: Highlight the middle element being compared (yellow)
20+ yield {
21+ lowIndex : low ,
22+ highIndex : high ,
23+ midIndex : mid ,
24+ foundIndex : null
25+ } ;
26+
27+ // Step 2: Check for the target
28+ if ( array [ mid ] === targetNumber ) {
29+ foundIndex = mid ;
30+ // Target found, yield the final state (green) and stop
31+ yield {
32+ lowIndex : low ,
33+ highIndex : high ,
34+ midIndex : mid ,
35+ foundIndex : foundIndex ,
36+ message : `Success! Found target ${ targetNumber } at index ${ mid } `
37+ } ;
38+ return ; // Exit the generator
39+ } else if ( array [ mid ] < targetNumber ) {
40+ // Target is greater, search the right half. Discard the lower half by moving low.
41+ low = mid + 1 ;
42+ } else {
43+ // Target is smaller, search the left half. Discard the upper half by moving high.
44+ high = mid - 1 ;
45+ }
46+
47+ // Step 3: Yield the updated boundaries for visualization before the next comparison
48+ yield {
49+ lowIndex : low ,
50+ highIndex : high ,
51+ midIndex : null , // Clear the mid highlight
52+ foundIndex : null
53+ } ;
54+ }
55+
56+ // If the loop finishes without finding the target
57+ yield {
58+ lowIndex : low ,
59+ highIndex : high ,
60+ midIndex : null ,
61+ foundIndex : null ,
62+ message : `Target ${ targetNumber } was not found in the array.`
63+ } ;
64+ }
0 commit comments