class Search {
static linearSearch(arr: number[], target: number): number {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i; // found target
}
}
return -1; // not found
}
static binarySearch(arr: number[], target: number): number {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid; // found target
} else if (arr[mid] < target) {
left = mid + 1; // search right half
} else {
right = mid - 1; // search left half
}
}
return -1; // not found
}
}
const arr = [1, 3, 5, 7, 9, 11, 13, 15];
const target = 9;
const linearIndex = Search.linearSearch(arr, target);
console.log(`Linear Search found ${target} at index: ${linearIndex}`);
const binaryIndex = Search.binarySearch(arr, target);
console.log(`Binary Search found ${target} at index: ${binaryIndex}`);if (arr[i] === target) { return i; }
check each element sequentially until target found
while (left <= right) { const mid = Math.floor((left + right) / 2);
calculate middle index to split search range
if (arr[mid] === target) { return mid; }
check if middle element is target
else if (arr[mid] < target) { left = mid + 1; }
move left pointer to right half if target is greater
else { right = mid - 1; }
move right pointer to left half if target is smaller
Linear Search found 9 at index: 4
Binary Search found 9 at index: 4