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