This is a simple R program to check whether an item is present in an array of elements. Here we are going to use Linear search algorithm/Sequential search algorithm for searching.
Linear search is the basic method used for searching an element in an array, list, or any other data structure. It is also called Sequential search because the element is searched sequentially in a list. There will be an array of elements and one element to search whether it belongs to the given set of elements.
As the name indicates Linear search compares the search element with the elements of the array one by one from the starting index to last. If a match is found it will output the index of array element where it got the match otherwise it gives an output ' item not found in the set '.
Unlike Binary search, Linear search is widely used to search an element in an unordered list i.e., the list containing elements that are not sorted. Although it is suitable for a smaller list (<100). Suppose there is a 10,000 element list and search element is available at the last position, sequential search will consume much time by comparing with each element of the list. Thus the worst-case time complexity of the linear search algorithm is O(n).
We can simply implement this algorithm with a for loop
and if condition
.
for loop
.forloop
, compare the search element with the current array element, and -print
the index of the corresponding array element and set a search flag with value 1 also break the loop.Let's go through an example for a better understanding,
for loop
from starting index(1) to last, and check whether the array element is equal to search element 4.
print
the array index where the item placed otherwise print
the message “element not found”.
STEP 1: Initialize the array arr with some predefined values in R.
STEP 2: Define variable item with a search value and flag with a zero for search status
STEP 3: Start a for loop
from one to the length of the array for comparing each element in the array.
STEP 4: Use an if condition
to check whether the element is equal to the search element, and
STEP 5: If the condition is true then print
the current array index and change the flag to 1, flag value 1 means we got our search element in the array, so break the for loop
STEP 6: otherwise for loop
will go for the next iteration until the end of the array.
STEP 7: Check if
the flag value is 0, yes means element not found.
arr= c(6,5,3,9,4,8) #array of elements
item=4 #search element
flag=0 #search status value
for (i in 1:length(arr)){ #array traversal
if (arr[i] == item) { #check for match
print(paste("element found at",i))
flag=1
break
}
}
if(flag==0) print("element not found")
[1] "element found at 5" [Execution complete with exit code 0]