diff --git a/Search/BinarySearch.js b/Search/BinarySearch.js index c5477cb7b9..77878f8f31 100644 --- a/Search/BinarySearch.js +++ b/Search/BinarySearch.js @@ -49,4 +49,52 @@ function binarySearchIterative(arr, x, low = 0, high = arr.length - 1) { return -1 } -export { binarySearchIterative, binarySearchRecursive } +/* binary search for unsorted arrays, returns original index. */ +function binarySearchOrigin(arr, target) { + // check if all elements in the array are of the same type + const firstType = typeof arr[0] + const allSameType = arr.every((item) => typeof item === firstType) + + if (!allSameType) { + return 'Cannot perform search: Array contains elements of different types.' + } + + const originalArrayWithIndices = arr.map((value, index) => ({ + value, + index + })) + + // sorting function based on type (number or string) + const sortedArrayWithIndices = originalArrayWithIndices.sort((a, b) => { + if (typeof a.value === 'number' && typeof b.value === 'number') { + return a.value - b.value // sort numbers + } else if (typeof a.value === 'string' && typeof b.value === 'string') { + return a.value.localeCompare(b.value) // sort strings + } + }) + + let start = 0 + let end = sortedArrayWithIndices.length - 1 + + // binary search loop + while (start <= end) { + const midIndex = Math.floor((start + end) / 2) + const mid = sortedArrayWithIndices[midIndex].value + + if (mid === target) { + // return the original index if the target is found + return sortedArrayWithIndices[midIndex].index + } + + if (mid < target) { + start = midIndex + 1 + } else { + end = midIndex - 1 + } + } + + // return -1 if target is not found + return -1 +} + +export { binarySearchIterative, binarySearchRecursive, binarySearchOrigin } diff --git a/Search/test/BinarySearch.test.js b/Search/test/BinarySearch.test.js index a903b4a24e..3e00ada235 100644 --- a/Search/test/BinarySearch.test.js +++ b/Search/test/BinarySearch.test.js @@ -1,4 +1,8 @@ -import { binarySearchIterative, binarySearchRecursive } from '../BinarySearch' +import { + binarySearchIterative, + binarySearchRecursive, + binarySearchOrigin +} from '../BinarySearch' const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const stringArr = [ @@ -31,7 +35,11 @@ const stringArr = [ ] describe('Binary Search', () => { - const funcs = [binarySearchIterative, binarySearchRecursive] + const funcs = [ + binarySearchIterative, + binarySearchRecursive, + binarySearchOrigin + ] for (const func of funcs) { test('expect to return the index of the item in the array', () => { expect(func(arr, 3)).toBe(2)