xxxxxxxxxx
this website explains linear searches well. It also has other searches and sorts as well.
https://computerneek.org/sortingal.html
xxxxxxxxxx
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.
xxxxxxxxxx
const linearSearch = (arr, item) => {
for (const i in arr) {
if (arr[i] === item) return +i;
}
return -1;
};
xxxxxxxxxx
#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;
}
xxxxxxxxxx
def linearsearch(arr, x):
for i in range(len(arr)):
#j=0
if arr[i] == x:
#j=j+1
return 1
#j=j+1
return -1
import random
import matplotlib.pyplot as plt
import time
timeList=[]
fornnumberList=[]
for i in range(6):
no=random.choice(range(20))#length
# print(no)
numList=random.sample(range(10,100,5),no)#for 'no' random numbers
num=random.choice(numList) #used for pivot or something
length=num
start_time=time.time()
linearsearch(numList,num)#enter the function here
print(linearsearch(numList, num))
end_time=time.time()
final_time= end_time- start_time
timeList.append(final_time)
fornnumberList.append(no)
print(timeList)
print(fornnumberList)
x=timeList
y=fornnumberList
plt.xlabel("Time taken")
plt.ylabel("For 'x' random numbers")
plt.plot(x, y)
plt.scatter(x, y)
xxxxxxxxxx
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