Linear Search
Definition​
- Definition
- Explanation
- Guidance
- Tips
Linear search is a simple searching algorithm that sequentially checks each element in a list until the desired element is found or the end of the list is reached. It is applicable to both ordered and unordered lists
Start by examining the first element of the list. Then, it progresses through each subsequent element in sequential order. At each step, the current element is compared with the target element. If a match is discovered, the algorithm returns the index of the found element. However, if the end of the list is reached without encountering the target element, the algorithm signals a failure to find the desired item
- Begin from the first element in the list
- Check each element in the list one by one
- If the current element matches the target, return its index
- If no match is found after checking all elements, return a failure signal
- linear search is straightforward but inefficient for large datasets compared to more optimized algorithms like binary search
- it's best suited for small lists or unordered lists where the elements are not arranged in any specific order
Practice​
- Practice
- Solution
linearSearch(list, target):
// Iterate through each element in the list
for index from 0 to length(list)-1:
// Check if the current element matches the target
if list[index] equals target:
// Return the index of the target element
return index
// If target not found, return a failure signal
return -1
package main
func linearSearch(arr []int, target int) int {
for i, v := range arr {
if v == target {
return i
}
}
return -1
}
public class LinearSearch {
public static int linearSearch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
}
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i;
}
}
return -1;
}
fun linearSearch(arr: IntArray, target: Int): Int {
for ((index, value) in arr.withIndex()) {
if (value == target) {
return index
}
}
return -1
}
def linear_search(arr, target):
for i, v in enumerate(arr):
if v == target:
return i
return -1
fn linear_search(arr: &[i32], target: i32) -> Option<usize> {
for (i, &val) in arr.iter().enumerate() {
if val == target {
return Some(i);
}
}
None
}
function linearSearch(arr: number[], target: number): number {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i;
}
}
return -1;
}