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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs