Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Implementing Linear Search in JavaScript
Linear search is a simple algorithm that sequentially checks each element in an array until the target element is found or the end of the array is reached. It has a time complexity of O(n) in the worst case.
How Linear Search Works
Basic Linear Search Function
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}
// Example usage
let numbers = [1, 19, 5, 11, 22, 55];
let target = 22;
let result = linearSearch(numbers, target);
console.log("Array:", numbers);
console.log("Target:", target);
console.log("Result:", result !== -1 ? `Found at index ${result}` : "Not found");
Array: [ 1, 19, 5, 11, 22, 55 ] Target: 22 Result: Found at index 4
Enhanced Linear Search with Details
function linearSearchDetailed(arr, target) {
console.log(`Searching for ${target} in array:`, arr);
for (let i = 0; i < arr.length; i++) {
console.log(`Step ${i + 1}: Checking arr[${i}] = ${arr[i]}`);
if (arr[i] === target) {
console.log(`? Found ${target} at index ${i}`);
return { index: i, steps: i + 1, found: true };
}
}
console.log(`? ${target} not found in array`);
return { index: -1, steps: arr.length, found: false };
}
// Test with different values
let testArray = [10, 25, 30, 45, 60];
// Search for existing element
linearSearchDetailed(testArray, 30);
console.log("---");
// Search for non-existing element
linearSearchDetailed(testArray, 99);
Searching for 30 in array: [ 10, 25, 30, 45, 60 ] Step 1: Checking arr[0] = 10 Step 2: Checking arr[1] = 25 Step 3: Checking arr[2] = 30 ? Found 30 at index 2 --- Searching for 99 in array: [ 10, 25, 30, 45, 60 ] Step 1: Checking arr[0] = 10 Step 2: Checking arr[1] = 25 Step 3: Checking arr[2] = 30 Step 4: Checking arr[3] = 45 Step 5: Checking arr[4] = 60 ? 99 not found in array
Browser Implementation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Linear Search Demo</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
padding: 20px;
}
.array-display {
font-size: 18px;
font-weight: bold;
color: #333;
margin: 10px 0;
}
.result {
font-size: 16px;
margin: 10px 0;
padding: 10px;
background-color: #f0f8ff;
border-left: 4px solid #007acc;
}
button {
background-color: #007acc;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
margin: 5px;
}
button:hover {
background-color: #005a9c;
}
</style>
</head>
<body>
<h1>Linear Search Demo</h1>
<div class="array-display">Array: [1, 19, 5, 11, 22, 55]</div>
<div class="result" id="result">Click a button to search</div>
<button onclick="searchFor(22)">Search for 22</button>
<button onclick="searchFor(5)">Search for 5</button>
<button onclick="searchFor(99)">Search for 99</button>
<script>
const arr = [1, 19, 5, 11, 22, 55];
function linearSearch(array, target) {
for (let i = 0; i < array.length; i++) {
if (array[i] === target) {
return i;
}
}
return -1;
}
function searchFor(target) {
const result = linearSearch(arr, target);
const resultDiv = document.getElementById('result');
if (result !== -1) {
resultDiv.innerHTML = `Found ${target} at index ${result}`;
resultDiv.style.color = 'green';
} else {
resultDiv.innerHTML = `${target} not found in the array`;
resultDiv.style.color = 'red';
}
}
</script>
</body>
</html>
Time Complexity Analysis
| Case | Time Complexity | Description |
|---|---|---|
| Best Case | O(1) | Element found at first position |
| Average Case | O(n/2) | Element found in middle of array |
| Worst Case | O(n) | Element at last position or not found |
Common Use Cases
// Finding first occurrence of a value
function findFirst(arr, target) {
return linearSearch(arr, target);
}
// Finding all occurrences
function findAll(arr, target) {
let indices = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
indices.push(i);
}
}
return indices;
}
// Search in array of objects
function searchByProperty(arr, property, value) {
for (let i = 0; i < arr.length; i++) {
if (arr[i][property] === value) {
return i;
}
}
return -1;
}
// Examples
let numbers = [3, 7, 2, 7, 1, 7];
let people = [
{name: "Alice", age: 25},
{name: "Bob", age: 30},
{name: "Charlie", age: 25}
];
console.log("All occurrences of 7:", findAll(numbers, 7));
console.log("Person with age 25:", searchByProperty(people, "age", 25));
All occurrences of 7: [ 1, 3, 5 ] Person with age 25: 0
Conclusion
Linear search is straightforward to implement and works on both sorted and unsorted arrays. While not the most efficient for large datasets, it's perfect for small arrays or when you need to search unsorted data. For sorted arrays, consider binary search for better performance.
Advertisements
