|
| 1 | +/* |
| 2 | +* Linear search or sequential search is a method for finding a target |
| 3 | +* value within a list. It sequentially checks each element of the list |
| 4 | +* for the target value until a match is found or until all the elements |
| 5 | +* have been searched. |
| 6 | +*/ |
| 7 | +function SearchArray(searchNum, ar) { |
| 8 | + var position = Search(ar, searchNum); |
| 9 | + if (position != -1) { |
| 10 | + console.log("The element was found at " + (position + 1)); |
| 11 | + } else { |
| 12 | + console.log("The element not found"); |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +// Search "theArray" for the specified "key" value |
| 17 | +function Search(theArray, key) { |
| 18 | + for (var n = 0; n < theArray.length; n++) |
| 19 | + if (theArray[n] == key) |
| 20 | + return n; |
| 21 | + return -1; |
| 22 | +} |
| 23 | + |
| 24 | +var ar = [1, 2, 3, 4, 5, 6, 7, 8, 9]; |
| 25 | +SearchArray(3, ar); |
| 26 | +SearchArray(4, ar); |
| 27 | +SearchArray(11, ar); |
0 commit comments