Python/C/C++/JAVA

Advanced Practice Programs with Code and Concept

By D.S

Linear Search Algorithm

Linear search, also known as sequential search, is a simple search algorithm that sequentially checks each element in a list until a match is found or the entire list has been searched. It works for both sorted and unsorted lists, making it a versatile algorithm for searching. This program demonstrates the linear search algorithm to find the position of a given element in an array.

(a.) C Code

#include <stdio.h>

      int linearSearch(int arr[], int n, int x) {
          for (int i = 0; i < n; i++) {
              if (arr[i] == x)
                  return i;
          }
          return -1;
      }
      
      int main() {
          int arr[] = {2, 3, 4, 10, 40};
          int n = sizeof(arr) / sizeof(arr[0]);
          int x = 10;
          int result = linearSearch(arr, n, x);
          if (result == -1)
              printf("Element is not present in array
");
          else
              printf("Element is present at index %d
", result);
          return 0;
      }
Output:-
Element is present at index 3

(b.) C++ Code

#include <iostream>
      using namespace std;
      
      int linearSearch(int arr[], int n, int x) {
          for (int i = 0; i < n; i++) {
              if (arr[i] == x)
                  return i;
          }
          return -1;
      }
      
      int main() {
          int arr[] = {2, 3, 4, 10, 40};
          int n = sizeof(arr) / sizeof(arr[0]);
          int x = 10;
          int result = linearSearch(arr, n, x);
          if (result == -1)
              cout << "Element is not present in array" << endl;
          else
              cout << "Element is present at index " << result << endl;
          return 0;
      }
Output:-
Element is present at index 3

(c.) Python Code

def linearSearch(arr, x):
    for i in range(len(arr)):
        if arr[i] == x:
            return i
    return -1
  
arr = [2, 3, 4, 10, 40]
x = 10
result = linearSearch(arr, x)
if result == -1:
    print("Element is not present in array")
else:
    print("Element is present at index", result)
Output:-
Element is present at index 3

(d.) Java Code

public class Main {
      public static int linearSearch(int[] arr, int x) {
          for (int i = 0; i < arr.length; i++) {
              if (arr[i] == x)
                  return i;
          }
          return -1;
      }
  
      public static void main(String[] args) {
          int[] arr = {2, 3, 4, 10, 40};
          int x = 10;
          int result = linearSearch(arr, x);
          if (result == -1)
              System.out.println("Element is not present in array");
          else
              System.out.println("Element is present at index " + result);
      }
  }
Output:-
Element is present at index 3

How did you feel about this post?

😍 🙂 😐 😕 😡

Was this helpful?

👍 👎