@@ -18,9 +18,11 @@ function binarySearchRecursive(array, search, offset = 0) {
18
18
19
19
if ( current === search ) {
20
20
return offset + half ;
21
- } if ( array . length === 1 ) {
21
+ }
22
+ if ( array . length === 1 ) {
22
23
return - 1 ;
23
- } if ( search > current ) {
24
+ }
25
+ if ( search > current ) {
24
26
const right = array . slice ( half ) ;
25
27
return binarySearchRecursive ( right , search , offset + half ) ;
26
28
}
@@ -38,50 +40,24 @@ function binarySearchRecursive(array, search, offset = 0) {
38
40
* @param {string|number } search value to search for
39
41
*/
40
42
function binarySearchIterative ( array , search ) {
41
- // console.log('binarySearchIterative', {array, search});
42
43
let start = 0 ;
43
- let end = array . length ;
44
- const half = ( ) => parseInt ( ( end - start ) / 2 , 10 ) + start ;
44
+ let end = array . length - 1 ;
45
+ const half = ( ) => start + parseInt ( ( end - start ) / 2 , 10 ) ;
45
46
46
- while ( end - start > 0 ) {
47
+ while ( start <= end ) {
47
48
const currentIndex = half ( ) ;
48
49
const current = array [ currentIndex ] ;
49
50
50
- if ( current === search ) {
51
- return currentIndex ;
52
- } if ( search > current ) {
53
- start = currentIndex ;
51
+ if ( current === search ) return currentIndex ;
52
+
53
+ if ( search > current ) {
54
+ start = currentIndex + 1 ;
54
55
} else if ( search < current ) {
55
- end = currentIndex ;
56
+ end = currentIndex - 1 ;
56
57
}
57
58
}
58
59
59
60
return - 1 ;
60
61
}
61
62
62
- // const binarySearch = binarySearchRecursive;
63
- const binarySearch = binarySearchIterative ;
64
-
65
- // function test() {
66
- // const directory = ['Adrian', 'Bella', 'Charlotte', 'Daniel',
67
- // 'Emma', 'Hanna', 'Isabella', 'Jayden', 'Kaylee', 'Luke', 'Mia',
68
- // 'Nora', 'Olivia', 'Paisley', 'Riley', 'Thomas', 'Wyatt', 'Xander', 'Zoe'];
69
- //
70
- // const assert = require('assert');
71
- // assert.equal(binarySearch([], 'not found'), -1);
72
- // assert.equal(binarySearch([1], 2), -1);
73
- // assert.equal(binarySearch([1], 1), 0);
74
- // assert.equal(binarySearch([1, 2, 3], 1), 0);
75
- // assert.equal(binarySearch([1, 2, 3], 2), 1);
76
- // assert.equal(binarySearch([1, 2, 3], 3), 2);
77
- // assert.equal(binarySearch([1, 2, 3], 31), -1);
78
- // assert.equal(binarySearch(directory, 'Adrian'), 0);
79
- // assert.equal(binarySearch(directory, 'Hanna'), 5);
80
- // assert.equal(binarySearch(directory, 'Zoe'), 18);
81
- // assert.equal(binarySearch(directory, 'not found'), -1);
82
- // }
83
-
84
- // test();
85
-
86
-
87
- module . exports = { binarySearch, binarySearchIterative, binarySearchRecursive } ;
63
+ module . exports = { binarySearchIterative, binarySearchRecursive } ;
0 commit comments