// Java Linear Search Algorithm
// ----------------------------
/*
Time Complexity
Best Time Complexity:O(1)
Average Time Complexity:O(n)
Worst Time Complexity:O(n)
Space Complexity
No auxiliary space is required in Linear Search implementation.
Hence space complexity is:O(1)
*/
class LinearSearch
{
public static int search(int arr[], int x)
{
int n = arr.length;
for (int i = 0; i < n; i++)
{
if (arr[i] == x)
return i;
}
return -1;
}
// Driver code
public static void main(String args[])
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
// Function call
int result = search(arr, x);
if (result == -1)
System.out.print(
"Element is not present in array");
else
System.out.print("Element is present at index "
+ result);
}
}
#include <bits/stdc++.h>
using namespace std;
int search(int arr[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;
return -1;
}
int main()
{
int arr[] = { 99,4,3,8,1 };
int key = 8;
int n = sizeof(arr) / sizeof(arr[0]);
int result = search(arr, n, key);
(result == -1)
? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
def linear_search(lst, target):
"""Returns the index position of the target if found, else returns -1"""
for i in range(0, len(lst)):
if lst[i] == target:
return i
return -1
A linear search is the simplest method of searching a data set. Starting at the beginning of the data set, each item of data is examined until a match is made. Once the item is found, the search ends.
const linearSearch = (arr, item) => {
for (const i in arr) {
if (arr[i] === item) return +i;
}
return -1;
};
"""
Ordered Linear Search
- This version searches for 1 item, and returns all the occurrences of it
"""
def ord_lin(lst, item):
found = []
# Search list up to larger number, and get all indices where its found
for i, num in enumerate(lst):
if num > item:
break
elif num == item:
found.append(i)
return found
# Linear Search:
"""
Another classic example of a brute force algorithm is Linear Search.
This involves checking each item in a collection to see if it is the
one we are looking for.
In Python, it can be implemented like this:
"""
arr = [42,2,3,1,4,6]
search_n = 2
for position, item in enumerate(arr):
if item == search_n:
print("%d The searching number is at position %d inside the array."%(search_n,position+1))
break
else:
print("Sorry! Not Found.")
"""
Of course there are many different implementations of this algorithm.
I like this one because it makes use of Python’s very handy enumerate function.
Regardless of the details of the implementation,
the basic idea remains the same – iterate through the collection (in the case above, a Python list),
and check if each item is the target.I like to use the variable names search_n and array from the
expression looking for a search_n in a array.
"""