Array: Linear Search


Arrays:

Arrays are a sequential collection of similar datatypes. They are stored in memory at adjacent memory locations.

Arrays are like neighbouring houses, each house has a Plot number or House number known as index in case of arrays. Each house has people who live in it similar to that the array has data at each memory location.

In the above example 0, 1, .., 4 are indexes and 1000.0, 2.0, ..., 50.0 are data values stored on those indexes.
# define an array 
arr = [1, 2, 7, 4, 5, 8, 0]

# print values of the array
# C for loop equivalent for array of length n => for(int i = 0; i < n; i++) 
for i in range(len(arr)):
     print(arr[i], end=' ')

# Output: 1 2 7 4 5 8 0

Arrays are generally used to store multiple values of similar datatype. Rather than defining 100 variable with 100 different names to store values we can define an array of size 100 and access each value by their array index.

Array Searching:

Searching an element in an array is a common use case and it can be done in many ways depending on the arrangement of elements in array.

Linear Search:

The linear search is a simple looking out at all the values in the array comparing each value (val) with the key (x) we want to search.

Algorithm:

# Given an array 'arr' and a key 'x' to be searched
for i from 0 to length(arr)-1:
   if arr[i] == x:
     return i 
   end if
end for
return -1

Code in Python 3:

Note: In python indentation is used to define scope or block of code. 

# Function for linear search
# inputs: array of elements 'arr', key to be searched 'x'
# returns: index of first occurrence of x in arr 
def linear_search(arr, x):

  # traverse the array
  for i in range(0, len(arr)):
    
    # if element at current index is same as x
    # return the index value
    if arr[i] == x:
      return i
      
  # if the element is not found in the array return -1
  return -1

Example:



Let the input array be: [1, 2, 6, 10, 13, 20, 25, 26, 27, 30] 
and x = 20.

1. i = 0, arr[i] = 1
    arr[i] != x
2. i = 1, arr[i] = 2
    arr[i] != x
3. i = 2, arr[i] = 6
    arr[i] != x
4. i = 3, arr[i] = 10
    arr[i] != x
5. i = 4, arr[i] = 13
    arr[i] != x
6. i = 5, arr[i] = 20
    arr[i] = x
    element found, return i = 5

Time Complexity: 

Time complexity is O(n) where 'n' is the number of elements in the array.
Runtime of our algorithm is linear as in the worst case, the key to be searched (x) would not be present in the array and we would end up searching the whole array.  

GeeksForGeeks: linear search example

--
Have any questions or suggestions? Post in the comments below!!

By,

Anubhav Shrimal

Comments

Popular posts from this blog

Segregate Even Odd value nodes in a linked list

Tree data structure

Reverse alternate k nodes in a linked list