|
| 1 | +/* Binary Search |
| 2 | +
|
| 3 | +Description: Binary Search finds the position of a target element in a sorted array by repeatedly dividing the search interval in half. If the value of the search key is less than the item in the middle of the interval, it narrows the interval to the lower half. Otherwise, it narrows it to the upper half. The search continues until the value is found or the interval is empty. |
| 4 | +
|
| 5 | +Prerequisites: The input array must be sorted in ascending order |
| 6 | +
|
| 7 | +Time Complexity: O(log n) |
| 8 | +Space Complexity: |
| 9 | +- Iterative: O(1) - constant space |
| 10 | +- Recursive: O(log n) - due to call stack |
| 11 | +
|
| 12 | +*/ |
| 13 | + |
| 14 | +function binarySearchIterative<T>(arr: T[], target: T): number { |
| 15 | + let left: number = 0; |
| 16 | + let right: number = arr.length - 1; |
| 17 | + |
| 18 | + while (left <= right) { |
| 19 | + const mid: number = Math.floor(left + (right - left) / 2); |
| 20 | + |
| 21 | + if (arr[mid] === target) { |
| 22 | + return mid; |
| 23 | + } |
| 24 | + |
| 25 | + if (arr[mid] < target) { |
| 26 | + left = mid + 1; |
| 27 | + } else { |
| 28 | + right = mid - 1; |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + return -1; |
| 33 | +} |
| 34 | + |
| 35 | +function binarySearchRecursive<T>( |
| 36 | + arr: T[], |
| 37 | + target: T, |
| 38 | + left: number = 0, |
| 39 | + right: number = arr.length - 1 |
| 40 | +): number { |
| 41 | + if (left > right) { |
| 42 | + return -1; |
| 43 | + } |
| 44 | + |
| 45 | + const mid: number = Math.floor(left + (right - left) / 2); |
| 46 | + |
| 47 | + if (arr[mid] === target) { |
| 48 | + return mid; |
| 49 | + } |
| 50 | + |
| 51 | + if (arr[mid] < target) { |
| 52 | + return binarySearchRecursive(arr, target, mid + 1, right); |
| 53 | + } else { |
| 54 | + return binarySearchRecursive(arr, target, left, mid - 1); |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +const sortedArray: number[] = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]; |
| 59 | + |
| 60 | +function runTests(): void { |
| 61 | + console.log("---------- Binary Search Test Cases ----------"); |
| 62 | + |
| 63 | + console.log("\nIterative Binary Search:"); |
| 64 | + console.log(`Finding 7: Index ${binarySearchIterative(sortedArray, 7)}`); // Should return 3 |
| 65 | + console.log(`Finding 15: Index ${binarySearchIterative(sortedArray, 15)}`); // Should return 7 |
| 66 | + console.log(`Finding 4: Index ${binarySearchIterative(sortedArray, 4)}`); // Should return -1 |
| 67 | + |
| 68 | + console.log("\nRecursive Binary Search:"); |
| 69 | + console.log(`Finding 7: Index ${binarySearchRecursive(sortedArray, 7)}`); // Should return 3 |
| 70 | + console.log(`Finding 15: Index ${binarySearchRecursive(sortedArray, 15)}`); // Should return 7 |
| 71 | + console.log(`Finding 4: Index ${binarySearchRecursive(sortedArray, 4)}`); // Should return -1 |
| 72 | +} |
| 73 | + |
| 74 | +runTests(); |
0 commit comments