Last active
March 24, 2022 11:36
-
-
Save AnkitMaheshwariIn/2296c0f03d179a2faceab30b2eb2118e to your computer and use it in GitHub Desktop.
Code to search an item from an array using linear search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* RUN THIS CODE AND OPEN YOUR CONSOLE TO SEE THE OUTPUT */ | |
// Code to search an item from an array using linear search | |
// declare a function which will take two arguments: array and itemToSearch | |
const doLinearSearch = (arr, itemToSearch) => { | |
// iterate using for loop, where i is index and elem is each item | |
for (const [i, elem] of arr.entries()) { | |
if (elem === itemToSearch) { | |
// return index, if elem matched with item to search | |
return i | |
} | |
} | |
} | |
// declare an array | |
arr = [10, 20, 30, 40, 50, 60] | |
// declare item to search | |
const itemToSearch = 50 | |
// call a function to search item from an array | |
// if item find this function will return index of an item | |
const itemIndex = doLinearSearch(arr, itemToSearch) | |
if (itemIndex > -1) { | |
console.log("Item found at index: " + itemIndex) | |
console.log("Item found is: " + arr[itemIndex]) | |
} else { | |
console.log("Item not found") | |
} | |
/* | |
THE OUTPUT IS: | |
"Item found at index: 4" | |
"Item found is: 50" | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment