Playground
Тестируйте и сравнивайте модели в реальном времени
Write a TypeScript function that implements a binary search algorithm.
Here's a clean TypeScript implementation of binary search: ```typescript function binarySearch<T>(arr: T[], target: T, compareFn?: (a: T, b: T) => number): number { const compare = compareFn ?? ((a: T, b: T) => (a < b ? -1 : a > b ? 1 : 0)); let left = 0; let right = arr.length - 1; while (left <= right) { const mid = Math.floor((left + right) / 2); const cmp = compare(arr[mid], target); if (cmp === 0) return mid; if (cmp < 0) left = mid + 1; else right = mid - 1; } return -1; // Not found } // Usage examples: const numbers = [1, 3, 5, 7, 9, 11, 13, 15]; console.log(binarySearch(numbers, 7)); // Output: 3 console.log(binarySearch(numbers, 6)); // Output: -1 // With custom comparator for objects: interface User { id: number; name: string } const users: User[] = [ { id: 1, name: "Alice" }, { id: 3, name: "Bob" }, { id: 5, name: "Charlie" }, ]; console.log(binarySearch(users, { id: 3, name: "" }, (a, b) => a.id - b.id)); // Output: 1 ``` Key features: - **Generic type support** — works with any comparable type - **Custom comparator** — optional comparison function for complex objects - **O(log n) time complexity** — efficient for sorted arrays - **Type-safe** — full TypeScript type inference
342
Всего токенов
$0.0085
Оценочная стоимость