A linear search is the simplest form of search in an array of elements. We can perform a linear search in three distinct ways based on the order of elements in an array.
There can be three scenarios, elements are in ascending order, or descending order, or no order at all.
If the array contains all the elements in ascending order, we’ll search for the element in the array starting from 0, till we encounter a number which is the finding number itself or a number which is greater than the finding number.
If the array contains all of its elements sorted in descending order, we’ll start searching from the 0th element till we find the number itself or a number which is smaller than the finding number.
Consider that we do not have the sorted the array. In this scenario, to find a number in this unsorted array, we must search through the all elements in that array till we reach the last element in the list.
The time complexity of linear search algorithm to find the number is O(n).
Linear Search in Java using an Unsorted Array
package com.techstackjournal;
public class LinearSearch {
public static void main(String[] args) {
int[] arr = { 20, 4, 18, 29, 42, 23, 48, 55 };
int fnum = 23;
int pos = findInUnsortedArray(arr, fnum);
if (pos >= 0) {
System.out.printf("Element found at %d position", pos);
} else {
System.out.println("Element not found");
}
}
public static int findInUnsortedArray(int[] arr, int fnum) {
int i;
for (i = 0; i < arr.length; i++) {
if (arr[i] == fnum) {
break;
}
}
if (i == arr.length) {
return -1;
} else {
return i;
}
}
}
Element found at 5 position
Linear Search in Java using an Ascending Ordered Array
public static int findInSortedAscArray(int[] arr, int fnum) {
int i;
for (i = 0; i < arr.length && arr[i] <= fnum; i++) {
if (arr[i] == fnum) {
break;
}
}
if (i == arr.length) {
return -1;
} else {
return i;
}
}
Linear Search in Java using Descending Ordered Array
public static int findInSortedDescArray(int[] arr, int fnum) {
int i;
for (i = 0; i < arr.length && arr[i] >= fnum; i++) {
if (arr[i] == fnum) {
break;
}
}
if (i == arr.length) {
return -1;
} else {
return i;
}
}
Linear Search in C using an Unsorted Array
#include <stdio.h>
int findInUnsortedArray(int arr[], int fnum)
{
int i;
for (i = 0; i < 8; i++)
{
if (arr[i] == fnum)
{
break;
}
}
if (i == 8)
{
return -1;
}
else
{
return i;
}
}
int main()
{
int arr[] = { 20, 4, 18, 29, 42, 23, 48, 55 };
int fnum = 23;
int pos = findInUnsortedArray(arr, fnum);
if (pos >= 0)
{
printf("Element found at %d position", pos);
}
else
{
printf("Element not found");
}
return 0;
}