Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 052e75c

Browse files
Chore: Completed Activity-2 for Day-18
1 parent cdc50bd commit 052e75c

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

‎Day18/index.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,46 @@ console.log("Quick Sort: ", quickSort(arr3));
7575
console.log("-------------------------------------------------");
7676
console.log("Activity 2: ");
7777

78+
// Task 4: Implement the linear search algorithm to find a target value in an array. Log the index of the target value.
79+
80+
const linearSearch = (arr, target) => {
81+
for (let i = 0; i < arr.length; i++) {
82+
if (arr[i] === target) {
83+
return i;
84+
}
85+
}
86+
return -1;
87+
}
88+
89+
let arr4 = [64, 34, 25, 12, 22, 11, 90];
90+
let target = 22;
91+
92+
console.log("Linear Search: ", linearSearch(arr4, target));
93+
94+
// Task 5: Implement the binary search algorithm to find a target value in a sorted array. Log the index of the target value.
95+
96+
const binarySearch = (arr, target) => {
97+
let left = 0;
98+
let right = arr.length - 1;
99+
100+
while (left <= right) {
101+
let mid = Math.floor((left + right) / 2);
102+
if (arr[mid] === target) {
103+
return mid;
104+
} else if (arr[mid] < target) {
105+
left = mid + 1;
106+
} else {
107+
right = mid - 1;
108+
}
109+
}
110+
return -1;
111+
}
112+
113+
let arr5 = [11, 12, 22, 25, 34, 64, 90];
114+
let target2 = 22;
115+
116+
console.log("Binary Search: ", binarySearch(arr5, target2));
117+
78118
console.log("-------------------------------------------------");
79119
console.log("Activity 3: ");
80120

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /