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

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay