This repository has been archived by the owner on Jan 16, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryVsLinearSearch.js
85 lines (69 loc) · 2.71 KB
/
BinaryVsLinearSearch.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
// Starting Fibonacci number
const number = 100;
const target = 34;
// below array is for Fibonacci Array
const newarray = [];
console.log('Fibonacci Series starting');
let n1 = 0, n2 = 1, nextTerm;
for (let i = 1; i <= number; i++) {
newarray.push(n1)
nextTerm = n1 + n2;
n1 = n2;
n2 = nextTerm;
}
console.log("The New Fibonacci array is " + newarray);
let linearCount = "";
//linearSearch
console.log("Starting to search through the Fibonacci array, using Linear search with a target of " + target);
linearSearch(newarray, target);
function linearSearch(arr, key) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === key) {
console.log("Using Linear Search the total iterations was " + i);
linearCount = i;
}
}
return -1
}
console.log("Starting to search through the Fibonacci array, using the Binary Search method");
let binaryCounter = "";
const binarySearch = (array, target) => {
// Define Start and End Index
let startIndex = 0;
let endIndex = array.length - 1;
// While Start Index is less than or equal to End Index
let counter = 0
while (startIndex <= endIndex) {
counter++
// Define Middle Index (This will change when comparing )
let middleIndex = Math.floor((startIndex + endIndex) / 2);
// Compare Middle Index with Target for match
if (target === array[middleIndex]) {
console.log("Using Binary Search the total iterations was " + counter);
binaryCounter = counter
return console.log("Target was found at index " + middleIndex);
}
// Search Right Side Of Array
if (target > array[middleIndex]) {
console.log("Searching the right side of Array")
// Assign Start Index and increase the Index by 1 to narrow search
startIndex = middleIndex + 1;
}
// Search Left Side Of Array
if (target < array[middleIndex]) {
// Assign End Index and increase the Index by 1 to narrow search
console.log("Searching the left side of array")
endIndex = middleIndex - 1;
}
// Not found in this iteration of the loop. Looping again.
else {
console.log("Not Found this loop iteration. Looping another iteration.")
}
}
// If Target Is Not Found
console.log("Target value not found in array");
}
binarySearch(newarray, target)
console.log("Total Binary Search iterations " + binaryCounter);
console.log("Total Linear Search iterations " + linearCount);
console.log("In conclusion " + (binaryCounter > linearCount ? "Binary" : "Linear") + " Search was more efficient by " + (linearCount - binaryCounter) + " iterations");