@@ -52,49 +52,49 @@ function binarySearchIterative(arr, x, low = 0, high = arr.length - 1) {
5252/* binary search for unsorted arrays, returns original index. */
5353function binarySearchOrigin ( arr , target ) {
5454 // 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 )
5757
5858 if ( ! allSameType ) {
59- return " Cannot perform search: Array contains elements of different types." ;
59+ return ' Cannot perform search: Array contains elements of different types.'
6060 }
6161
6262 const originalArrayWithIndices = arr . map ( ( value , index ) => ( {
6363 value,
64- index,
65- } ) ) ;
64+ index
65+ } ) )
6666
6767 // sorting function based on type (number or string)
6868 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
7373 }
74- } ) ;
74+ } )
7575
76- let start = 0 ;
77- let end = sortedArrayWithIndices . length - 1 ;
76+ let start = 0
77+ let end = sortedArrayWithIndices . length - 1
7878
7979 // binary search loop
8080 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
8383
8484 if ( mid === target ) {
8585 // return the original index if the target is found
86- return sortedArrayWithIndices [ midIndex ] . index ;
86+ return sortedArrayWithIndices [ midIndex ] . index
8787 }
8888
8989 if ( mid < target ) {
90- start = midIndex + 1 ;
90+ start = midIndex + 1
9191 } else {
92- end = midIndex - 1 ;
92+ end = midIndex - 1
9393 }
9494 }
9595
9696 // return -1 if target is not found
97- return - 1 ;
97+ return - 1
9898}
9999
100100export { binarySearchIterative , binarySearchRecursive , binarySearchOrigin }
0 commit comments