Skip to content

Commit 644557f

Browse files
Merge pull request #9 from anasmak04/master
add binary search
2 parents b72706f + 911f361 commit 644557f

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
| Problem - 44 | [ swap ](https://github.com/anasmak04/Problem-solving-with-JavaScript/blob/master/problem-44.js) |
4949
| Problem - 45 | [ max two numbers ](https://github.com/anasmak04/Problem-solving-with-JavaScript/blob/master/problem-45.js) |
5050
| Problem - 46 | [ Sort an Array without using any built-in functions ](https://github.com/anasmak04/Problem-solving-with-JavaScript/blob/master/problem-46.js) |
51+
| Problem - 47 | [ Binary Search ](https://github.com/anasmak04/Problem-solving-with-JavaScript/blob/master/problem-47.js) |
5152

5253

53-
<!-- | Problem - 47 | | -->
54+
<!-- | Problem - 48 | | -->

problem-47.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Given an array of integers nums which is sorted in ascending order,
2+
// and an integer target, write a function to search target in nums.
3+
// If target exists, then return its index. Otherwise, return -1.
4+
// You must write an algorithm with O(log n) runtime complexity.
5+
6+
7+
let search = function (nums, target) {
8+
let array = nums.sort(function (a, b) { return a - b });
9+
let firstIndex = 0;
10+
let lastIndex = array.length - 1;
11+
while (firstIndex <= lastIndex) {
12+
let middleIndex = Math.floor((firstIndex + lastIndex) / 2);
13+
if (target == array[middleIndex]) {
14+
return middleIndex
15+
}
16+
if (target < array[middleIndex]) {
17+
lastIndex = middleIndex - 1;
18+
}
19+
else {
20+
firstIndex = middleIndex + 1;
21+
}
22+
}
23+
return -1
24+
};
25+
26+
// Example 1:
27+
28+
// Input: nums = [-1,0,3,5,9,12], target = 9
29+
// Output: 4
30+
// Explanation: 9 exists in nums and its index is 4
31+
// Example 2:
32+
33+
// Input: nums = [-1,0,3,5,9,12], target = 2
34+
// Output: -1
35+
// Explanation: 2 does not exist in nums so return -1

0 commit comments

Comments
 (0)