8000 Merge pull request #12 from brendanAlbert/master · AllAlgorithms/javascript@17883c1 · GitHub
[go: up one dir, main page]

Skip to content

Commit 17883c1

Browse files
authored
Merge pull request #12 from brendanAlbert/master
Create binarySearch.js
2 parents 19a613e + 9bcd851 commit 17883c1

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

searching/binarySearch.js

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/**
2+
JavaScript implementation of the binary search algorithm.
3+
4+
Author: Brendan Albert
5+
6+
This is a JavaScript iterative (rather than recursive) implementation of the binary search algorithm.
7+
8+
The binary search algorithm works by looking at the middle element of a list.
9+
The list must be sorted to work correctly.
10+
This implementation uses ascending order.
11+
12+
If the value being searched for is not the middle element, then we check
13+
if the value is smaller or larger than the middle element.
14+
15+
This allows the size of the list being searched to be halved each iteration.
16+
17+
The big O runtime of this algorithm is log(n).
18+
Log(n) is nice because it means that given a huge list, say of 1 million IDs,
19+
it will take no more than 20 iterations to determine if the ID is present.
20+
21+
Arguments: value (that we are searching for), list_to_search (the list)
22+
23+
Return: the value if it is found in the list or -1 if the value is not found.
24+
*/
25+
function binarySearch(value, list_to_search) {
26+
27+
search_value = -1
28+
max_index = list_to_search.length - 1
29+
min_index = 0
30+
middle_index = Math.floor( (max_index + min_index) / 2)
31+
current_element = list_to_search[middle_index]
32+
33+
while (max_index >= min_index) {
34+
35+
if (current_element == value)
36+
return current_element
37+
38+
else if (value > current_element)
39+
min_index = middle_index + 1
40+
41+
else if (value < current_element)
42+
max_index = middle_index - 1
43+
44+
middle_index = Math.floor( (min_index + max_index) / 2)
45+
current_element = list_to_search[middle_index]
46+
47+
}
48+
49+
return search_value
50+
}
51+
52+
// Sample lists to test with
53+
id_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
54+
odd_list = [1,3,5,7,9,11,13,15,17,19]
55+
short_list = ['allie', 'ben', 'charlie', 'danielle', 'emilio', 'fred', 'gina', 'henry', 'isabella']
56+
57+
console.log(binarySearch(3, odd_list))

0 commit comments

Comments
 (0)
0