-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbinary.js
117 lines (99 loc) · 2.35 KB
/
binary.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
function bin(list, num){
let left = 0;
let right = list.length -1;
while (left <= right) {
let mid = Math.floor((right + left)/2);
if (num === list[mid]){
return mid;
}
else if (num > list[mid]){
left = mid + 1;
}
else{
right = mid - 1;
}
}
}
// console.log(bin([4,5,6,7,8,9,2,1], 1));
function myBin(newList, n)
{
let left = 0;
let right = newList.length -1;
while(left <= right)
{
let mid = Math.floor((left + right)/2);
if(n < newList[mid])
{
return right -1;
}
else if( n > newList[mid])
{
return left + 1;
}
else if ( n === newList[mid] )
{
return mid ;
}
else
{
return "Number doesnt exist";
}
}
}
// console.log(myBin([7,5,3,4,8,1,6],8))
function myBin(newList, n)
{
let left = 0;
let right = newList.length - 1;
while (left <= right)
{
let mid = Math.floor((left + right) / 2);
if (n < newList[mid])
{
right = mid - 1;
return right;
}
else if (n > newList[mid])
{
left = mid + 1;
return left;
}
else if (n === newList[mid])
{
return mid;
}
}
return `Number ${n} doesn't exist`;
}
// console.log(myBin([15, 8, 2, 11, 19, 6, 4, 10, 5, 14, 1, 13, 7, 20, 3, 12, 18, 9, 17, 16], 2));
// console.log(bin([7,5,3,4,8,1,6],5))
// we had some inefficiency in our previous binary search and now we are to improve it
//we will be sorting our data to improve the efficiency of our data structure
function newBin(mylist, n)
{
//sorting the array using quick sort method
let _sorted = mylist.sort();
let left = 0;
let right = _sorted.length -1;
while (left <= right)
{
let mid = Math.floor((left + right)/ 2);
if (n === _sorted[mid] )
{
return mid;
}
else if(n > _sorted[mid])
{
return right ;
}
else if (n < _sorted[mid])
{
return left;
}
else
{
return `The number ${n} is not found in the list ${mylist}`;
}
}
}
console.log(newBin([7,5,3,4,8,1,6],4));