// Java Linear Search Algorithm
// ----------------------------
/*
Time Complexity
Best Time Complexity:O(1)
Average Time Complexity:O(n)
Worst Time Complexity:O(n)
Space Complexity
No auxiliary space is required in Linear Search implementation.
Hence space complexity is:O(1)
*/
class LinearSearch
{
public static int search(int arr[], int x)
{
int n = arr.length;
for (int i = 0; i < n; i++)
{
if (arr[i] == x)
return i;
}
return -1;
}
// Driver code
public static void main(String args[])
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
// Function call
int result = search(arr, x);
if (result == -1)
System.out.print(
"Element is not present in array");
else
System.out.print("Element is present at index "
+ result);
}
}
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package com.SortingAlgorithm;
import java.util.Scanner;
public class LinearSearch {
public LinearSearch() {
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of Element you want: ");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter " + n + " values");
int target;
for(target = 0; target < n; ++target) {
arr[target] = sc.nextInt();
}
System.out.println("Enter the value of target Element: ");
target = sc.nextInt();
for(int i = 0; i < n; ++i) {
if (arr[i] == target) {
System.out.println("Element found at index: " + i);
break;
}
System.out.println("Element not found at index: " + i);
}
}
}
Step 1: Traverse the array
Step 2: Match the key element with array element
Step 3: If key element is found, return the index position of the array element
Step 4: If key element is not found, return -1