Understand Linear Search Problem

Problem Name: Linear Search
Problem Description:

Linear Search Algorithm Explained

Linear search is one of the simplest search algorithms. It sequentially checks each element in a list until the desired element (the target) is found or the list ends. This approach works on both sorted and unsorted lists, making it versatile for small datasets.


How Linear Search Works

  1. Iteration: Start at the beginning of the list.
  2. Comparison: Compare each element with the target value.
  3. Match Found: If an element matches the target, return its index.
  4. Completion: If no match is found by the end of the list, return an indicator (typically -1).

Time Complexity Table

ScenarioTime ComplexityExplanation
Best CaseO(1) The target is the first element in the list.
Average CaseO(n)The target is somewhere in the middle of the list.
Worst CaseO(n) The target is the last element or is not present at all.

Key Takeaways

  • Simplicity: Linear search is easy to implement and understand.
  • No Preprocessing: It works without requiring the list to be sorted.
  • Efficiency: While efficient for small or unsorted datasets, it is less effective for large datasets due to its O(n) time complexity.
  • Versatility: It can be applied to any list regardless of order.

Category:
  • Searching & Sorting
Programming Language:
  • Java
Reference Link:

https://drawtocode.vercel.app/problems/linear-search

Online IDE

Scroll down for output
Java
Output:

Loading component...

Loading component...

Tracking code (View only. In case you want to track the code, click this button):
Main Function:

INPUT: [8, 3, 5, 4, 2, 7, 6, 1] ,3

OUTPUT: 1

public static void main(String args[]){

int arr[] = { 12, 11, 13, 5, 6, 7 };

int ans = linearSearch( arr,5);

if (ans == -1) {

System.out.print("Element is not present in array");

}//If End

else {

System.out.print("Element is present at index " + ans );

}//Else End

}//function end

Helper Function:

public static int linearSearch(int[] arr, int target) {

for (int i = 0; i < arr.length; i++) {

if (arr[i] == target) {

return i;

}//If End

}//Loop End

return -1;

}//function end

Utility Functions and Global variables:

Utility Function is not required.