We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent d8759ae commit 764f067Copy full SHA for 764f067
binary-search/main.js
@@ -0,0 +1,30 @@
1
+/**
2
+ * @param {number[]} nums
3
+ * @param {number} target
4
+ * @return {number}
5
+ */
6
+var search = function(nums, target) {
7
+ let l = 0;
8
+ let r = nums.length - 1;
9
+
10
+ while (l <= r) {
11
+ // important : to get the middle of array
12
+ let mid = Math.floor((l + r) / 2);
13
14
+ // if the target found
15
+ if (nums[mid] == target) {
16
+ return mid;
17
+ }
18
19
+ // if the target is less than the current mid value
20
+ if (nums[mid] < target) {
21
+ l = mid + 1; // the current mid is left
22
+ } else {
23
+ r = mid - 1; // the current mid is right
24
25
26
27
+ // target not found in array
28
+ return -1;
29
+};
30
0 commit comments