How to use Linear Search In Javascript
Linear search is a type of brute force method that works on linear traversal of the array. It searches the target in O(N) time. It works whether the array is sorted or not.
The program will run till the target is not found and will stop when the first occurrence is matched.
Example: In this example. we will use linear search to get the first index of target element.
// Input array
arr = [1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 8, 8, 9];
// Target element
target = 5;
// Iterate till length of array
for (let i = 0; i < arr.length; ++i) {
// If target found return and exit program
if (arr[i] === target) {
console.log(
"First index of " + target + " is: " + i
);
return;
}
}
// If not found display output
console.log(target + " is not present in the given array");
Output
First index of 5 is: 4
JavaScript Program to Find Index of First Occurrence of Target Element in Sorted Array
In this article, we will see the JavaScript program to get the first occurrence of a number in a sorted array. We have the following methods to get the first occurrence of a given number in the sorted array.