WikiGalaxy

Personalize

Linear Search

Introduction to Linear Search

Linear search is a straightforward searching algorithm that checks each element in a list sequentially until the desired element is found or the list ends. It is simple but not efficient for large datasets.

Example 1: Linear Search in an Array of Integers

This example demonstrates a linear search algorithm applied to an array of integers to find a specific number.


int linearSearch(int[] arr, int x) {
  for (int i = 0; i < arr.length; i++) {
    if (arr[i] == x) {
      return i;
    }
  }
  return -1;
}
      

Console Output:

Element found at index: 3

Example 2: Linear Search in a List of Strings

This example uses linear search to find a particular string in a list of names.


int linearSearch(String[] arr, String target) {
  for (int i = 0; i < arr.length; i++) {
    if (arr[i].equals(target)) {
      return i;
    }
  }
  return -1;
}
      

Console Output:

Name found at index: 2

Example 3: Linear Search in a Linked List

Here, linear search is implemented on a linked list to find a specific node value.


int linearSearch(LinkedList list, int x) {
  for (int i = 0; i < list.size(); i++) {
    if (list.get(i) == x) {
      return i;
    }
  }
  return -1;
}
      

Console Output:

Node found at index: 5

Example 4: Linear Search in a Character Array

This example shows how linear search can be used to find a character in an array of characters.


int linearSearch(char[] arr, char target) {
  for (int i = 0; i < arr.length; i++) {
    if (arr[i] == target) {
      return i;
    }
  }
  return -1;
}
      

Console Output:

Character found at index: 1

Example 5: Linear Search in a List of Objects

In this example, linear search is applied to a list of custom objects to find an object with a specific property.


class Product {
  String name;
  int id;
  
  Product(String name, int id) {
    this.name = name;
    this.id = id;
  }
}

int linearSearch(List products, int targetId) {
  for (int i = 0; i < products.size(); i++) {
    if (products.get(i).id == targetId) {
      return i;
    }
  }
  return -1;
}
      

Console Output:

Product found at index: 4

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025