Skip to content

Commit 51a484d

Browse files
committed
feat: add binary search origin algorithm
1 parent 5b17ea1 commit 51a484d

File tree

2 files changed

+51
-3
lines changed

2 files changed

+51
-3
lines changed

Search/BinarySearch.js

+49-1
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,52 @@ function binarySearchIterative(arr, x, low = 0, high = arr.length - 1) {
4949
return -1
5050
}
5151

52-
export { binarySearchIterative, binarySearchRecursive }
52+
/* binary search for unsorted arrays, returns original index. */
53+
function binarySearchOrigin(arr, target) {
54+
// check if all elements in the array are of the same type
55+
const firstType = typeof arr[0];
56+
const allSameType = arr.every((item) => typeof item === firstType);
57+
58+
if (!allSameType) {
59+
return "Cannot perform search: Array contains elements of different types.";
60+
}
61+
62+
const originalArrayWithIndices = arr.map((value, index) => ({
63+
value,
64+
index,
65+
}));
66+
67+
// sorting function based on type (number or string)
68+
const sortedArrayWithIndices = originalArrayWithIndices.sort((a, b) => {
69+
if (typeof a.value === "number" && typeof b.value === "number") {
70+
return a.value - b.value; // sort numbers
71+
} else if (typeof a.value === "string" && typeof b.value === "string") {
72+
return a.value.localeCompare(b.value); // sort strings
73+
}
74+
});
75+
76+
let start = 0;
77+
let end = sortedArrayWithIndices.length - 1;
78+
79+
// binary search loop
80+
while (start <= end) {
81+
const midIndex = Math.floor((start + end) / 2);
82+
const mid = sortedArrayWithIndices[midIndex].value;
83+
84+
if (mid === target) {
85+
// return the original index if the target is found
86+
return sortedArrayWithIndices[midIndex].index;
87+
}
88+
89+
if (mid < target) {
90+
start = midIndex + 1;
91+
} else {
92+
end = midIndex - 1;
93+
}
94+
}
95+
96+
// return -1 if target is not found
97+
return -1;
98+
}
99+
100+
export { binarySearchIterative, binarySearchRecursive, binarySearchOrigin }

Search/test/BinarySearch.test.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { binarySearchIterative, binarySearchRecursive } from '../BinarySearch'
1+
import { binarySearchIterative, binarySearchRecursive, binarySearchOrigin } from '../BinarySearch'
22

33
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
44
const stringArr = [
@@ -31,7 +31,7 @@ const stringArr = [
3131
]
3232

3333
describe('Binary Search', () => {
34-
const funcs = [binarySearchIterative, binarySearchRecursive]
34+
const funcs = [binarySearchIterative, binarySearchRecursive, binarySearchOrigin]
3535
for (const func of funcs) {
3636
test('expect to return the index of the item in the array', () => {
3737
expect(func(arr, 3)).toBe(2)

0 commit comments

Comments
 (0)