Created
January 31, 2026 12:33
-
-
Save Toomean/f5a9f382ae83014b1565e98375db510a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Classic Binary Search (Model: "The Vise") | |
| * * Time Complexity: O(log n) | |
| * Space Complexity: O(1) | |
| */ | |
| export function binarySearch(nums: number[], target: number): number { | |
| let left = 0; | |
| let right = nums.length - 1; | |
| while (left <= right) { | |
| // Prevent Integer Overflow: L + (R - L) / 2 | |
| // In JS/TS this isn't critical (Numbers are float64), but for C++/Java/Rust this is standard practice. | |
| const mid = left + Math.floor((right - left) / 2); | |
| if (nums[mid] === target) { | |
| return mid; | |
| } | |
| if (nums[mid] < target) { | |
| // mid is too small (trash). | |
| // Move the left jaw PAST the trash. | |
| left = mid + 1; | |
| } else { | |
| // mid is too big (trash). | |
| // Move the right jaw BEFORE the trash. | |
| right = mid - 1; | |
| } | |
| } | |
| return -1; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment