Data structures and algorithm tutorial: linear search algorithm
Showing posts with label linear search algorithm. Show all posts
Showing posts with label linear search algorithm. Show all posts

Saturday, September 12, 2020

linear search algorithm and its program in c

September 12, 2020 0
linear search algorithm and its program in c
In this tutorial, you'll study the linear search algorithm. you'll also find functional samples of linear search C programming, C ++, Java, and Python.

Linear search is the simplest search algorithm that searches for an item during a list in sequential order. We start at one end and check each item until the item we would like isn't found.

How does the linear search algorithm work?

  • The following steps are followed to seek out a component k = 1 within the list below.

linear search algorithm


  • Start with the primary element, compare k with each element x.

 

Linear Search in c
Linear Search in c

  • If x == k, return the index.
linear search
linear search 


 Linear Search Algorithm

 Linear Search Algorithm
 Linear Search Algorithm

 Linear Search Program In C



#include <stdio.h>

int search(int array[], int n, int x) {
  
  // Going through array sequencially
  for (int i = 0; i < n; i++)
    if (array[i] == x)
      return i;
  return -1;
}

int main() {
  int array[] = {2, 4, 0, 1, 9};
  int x = 1;
  int n = sizeof(array) / sizeof(array[0]);

  int result = search(array, n, x);

  (result == -1) ? printf("Element not found") : printf("Element found at index: %d", result);
}

Otherwise, return not found.

Complexities For linear search Algorithm


Time complexity: O (n)

Spatial complexity: O (1)


Use Of Linear Search Algorithm

Let's say you would like to look for a component (x) during a given array (arr)

the primary and foremost algorithm that might strike an individual is to iterate through each element of the array and check whether or not it's adequate to the search element (x).
 

 This type of algorithm is known as a Linear Search Algorithm in Data Structure.