This content originally appeared on DEV Community and was authored by Md Qayyum Shareef
Hi there, In Linear Search or Sequential Search every element in the array is checked, and if the match is found then the element index is returned, otherwise the search continues till the last element.
Visual learners can follow my YouTube video.
Lets write some code
always remember that array indexing starts from Zero - '0'
const numbers = [2, 4, 67, 8, 44, 6, 12];
Now, lets write a function to apply linear search algorithm to above array.
function linearSearch(array, num) {
for (let i = 0; i < array.length; i++) {
if (array[i] === num) {
return i;
}
}
return -1;
}
linearSearch(numbers, 8); // returns index 4
linearSearch(numbers, 28); // since 28 is not there, returns -1
// Save the file and run it using Node.JS
// Open terminal and give command: node [filename].js
Time Complexity
The time complexity for the above code is O(n).
let's improve the worst case scenario.
- If the search element found at last. O(n) -> O(1)
- If the search element not found. O(n) -> O(n/2)
function betterLinearSearch(array, element) {
let length = array.length;
let left = 0;
let right = length - 1;
let position = -1;
while (left <= right) {
if (array[left] == element) {
position = left;
console.log(`${element} is present at index ${position}. attempt ${left + 1}`);
break;
}
if (array[right] == element) {
position = right;
console.log(`${element} is present at index ${position}. - attempt ${length - right}`);
break;
}
left++;
right--;
}
if (position == -1) {
console.log(`${element} not found. attempt ${left}`);
}
}
betterLinearSearch(numbers, 8);
// Try with a last element and check the attempts in log
betterLinearSearch(numbers, 12);
betterLinearSearch(numbers, 28);
// Save the file and run it using Node.JS
// Open terminal and give command: node [filename].js
- In every iteration, first and last element from the array is being checked.
- After every iteration the left index needed to be increased and right index needed to be decreased.
- When position value remains
-1it means the element is not present in array.
Well, that's it for this article. I hope you learned something. Follow me for more posts just like this and let me know your thoughts in the comment section.
Share this post with your friends who needs to learn algorithms. Thanks
This content originally appeared on DEV Community and was authored by Md Qayyum Shareef
Md Qayyum Shareef | Sciencx (2021-08-19T19:39:40+00:00) Linear Search Algorithm | JavaScript. Retrieved from https://www.scien.cx/2021/08/19/linear-search-algorithm-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.