forked from lindakwoo/Udemy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.js
81 lines (72 loc) · 1.92 KB
/
search.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
function linearSearch(arr, value){
let i=0;
for(let item of arr){
if(item===value){
return i;
}
i++;
}
return -1;
}
// console.log(linearSearch([7,5,6,4],10))
function binarySearch(arr,num){
let start = 0;
let end = arr.length-1;
let mid = Math.floor(((end-start)/2)+start);
console.log(start, end, mid);
while(start!==end){
if(arr[mid]===num){
return mid;
}
else if(arr[mid]>num){
end = mid-1;
mid = Math.floor(((end-start)/2)+start);
}
else {
start = mid+1;
mid = Math.floor(((end-start)/2)+start);
}
console.log(start, end, mid);
}
if(arr[start]===num){
return start;
}
return -1;
}
// console.log(binarySearch([1,3,5,12,34,56],9));
// let naiveSearch = (short, long)=>{
// console.log(short.length,long.length);
// let counter = 0;
// let j;
// for(let i = 0;i<(long.length-short.length);i++){
// j=0;
// while(j<short.length){
// if(short[j]===long[i+j]){
// if(j===short.length-1){
// counter++;
// j++;
// }
// else{
// j++;
// }
// }
// else {
// j=short.length;
// }
// }
// }
// return counter;
// }
// console.log(naiveSearch("apa", "appapapae"))
let naiveSearch = (short, long)=>{
console.log(short.length,long.length);
let counter = 0;
for(let i = 0;i<(long.length-short.length);i++){
for(let j = 0;j<short.length;j++){
if(short[j]!==long[i+j]) break;
if(j===short.length-1) counter++;
}
}
return counter;
}
// console.log(naiveSearch("apa", "appapapae"))