-
Notifications
You must be signed in to change notification settings - Fork 0
/
searching.js
75 lines (61 loc) · 2.65 KB
/
searching.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
/**
Searching algorithms are used to find a specific element within a collection of data.
They are fundamental to solving various problems efficiently. Different searching algorithms have different characteristics,
such as time complexity and the requirement for the data to be sorted.
The choice of the searching algorithm depends on the problem requirements and the characteristics of the data.
*/
class Searching {
/**
Searching Algorithm Example: Linear Search:
Linear Search is a simple searching algorithm that sequentially checks each element of the data structure until it finds the target element
or reaches the end of the collection. It is applicable to both sorted and unsorted data.
*/
linearSearch(array, target) {
for (let i = 0; i < array.length; i++) {
if (array[i] === target) {
return i; // Return the index of the target element
}
}
return -1; // Target element not found
}
/**
Searching Algorithm Example: Binary Search:
Binary Search is a searching algorithm that works efficiently on sorted arrays.
It follows a divide-and-conquer approach by repeatedly dividing the search space in half until the target element is found or the search space is exhausted.
Binary Search eliminates half of the remaining elements in each step, making it significantly faster than linear search.
*/
binarySearch(array, target) {
array.sort(function(a, b){return a-b})
let left = 0;
let right = array.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (array[mid] === target) {
return mid; // Return the index of the target element
} else if (array[mid] < target) {
left = mid + 1; // Target is in the right half
} else {
right = mid - 1; // Target is in the left half
}
}
return -1; // Target element not found
}
}
// Example Usage
const searching = new Searching();
const array = [10, 7, 5, 2, 8]; // Example array
const target = 5; // Element to search for
// Linear Search
const index = searching.linearSearch(array, target);
if (index !== -1) {
console.log(`Linear Search: Element ${target} found at index ${index}`);
} else {
console.log(`Linear Search: Element ${target} not found`);
}
// Binary Search
const indexBinary = searching.binarySearch(array, target);
if (indexBinary !== -1) {
console.log(`Binary Search: Element ${target} found at index ${index}`);
} else {
console.log(`Binary Search: Element ${target} not found`);
}