@@ -75,6 +75,46 @@ console.log("Quick Sort: ", quickSort(arr3));
75
75
console . log ( "-------------------------------------------------" ) ;
76
76
console . log ( "Activity 2: " ) ;
77
77
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
+
78
118
console . log ( "-------------------------------------------------" ) ;
79
119
console . log ( "Activity 3: " ) ;
80
120
0 commit comments