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.
#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;
}
#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;
}
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)
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);
}
}
Was this helpful?