-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearch.js
96 lines (87 loc) · 2.24 KB
/
BinarySearch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Binary search is a search algorithm that finds the position of
// a target value within a sorted array. It works by repeatedly dividing
// in half the portion of the array that could contain the target value until the value
// is found or the remaining portion of the array is empty.
//example array = [5, 10, 15, 20, 25];
function Binarysearch(array, target) {
const left = 0;
const right = array.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
const value = array[mid];
if (value === target) {
return mid;
} else if (value < target) {
left = mid + 1
} else {
right = mid - 1
}
}
return -1;
}
const array = [5, 10, 15, 20, 25];
const target = 15;
console.log(Binarysearch(array, target));
// Binary search tree
//A tree is a collection of nodes connected by some edges
class Node {
constructor(data, left = null, right = null) {
this.data = data;
this.left = left;
this.right = right;
}
}
class BST {
constructor() {
this.root = null;
}
add(data) {
const node = this.root;
if (node === null) {
// Creating a node and initialising
// with data
this.root = new Node(data);
return;
} else {
const searchTree = (node) => {
// if the data is less than the node
// data move left of the tree
if (data < node.data) {
if (node.left === null) {
// if left is null insert node here
node.left = new Node(data);
return;
} else if (node.left !== null) {
// if left is not null recur until
// null is found
return searchTree(node.left);
}
}
else{
if (node.right === null) {
node.right = new Node(data);
return;
} else if (node.right !== null) {
// if right is not null recur until
// null is found
return searchTree(node.right);
} else {
return null;
}
}
};
}
}
}
const data = new BST();
data.add(15);
data.add(25);
data.add(10);
data.add(7);
data.add(22);
data.add(17);
data.add(13)
data.add(5)
data.add(9)
data.add(27)
console.log(data);