DEV Community

Cover image for Linear Search Examples
Jack Pritom Soren
Jack Pritom Soren

Posted on

Linear Search Examples

Example in C :

#include <stdio.h>

int search(int array[], int n, int x) {

  // Going through array sequencially

  int i;
  for (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);

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

Enter fullscreen mode Exit fullscreen mode

Example in JavaScript :


function linearSearch(arr, item) {

    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === item) {
            return i;
        }
    }
    return null;
}

var array = [1, 2, 3, 4];

var search = 4;

var result = linearSearch(array, search);

if(result === null)
{
    console.log('The item is not found');
}
else
{
    console.log('The item is found at index '+result)
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)