Linear search is a simple search algorithm

Category : Data-structures-algorithms | Sub Category : Linear search | By Prasad Bonam Last updated: 2023-08-14 12:56:10 Viewed : 307


Linear search is a simple search algorithm:

Linear search is a simple search algorithm that iterates through an array (or a list) to find a specific element. It sequentially checks each element of the array until a match is found or the entire array has been searched.

Here is an example of linear search in Java along with its output:

java
public class LinearSearchExample { public static void main(String[] args) { int[] array = {12, 45, 6, 8, 23, 17, 42}; int target = 23; int index = linearSearch(array, target); if (index != -1) { System.out.println("Element " + target + " found at index " + index); } else { System.out.println("Element " + target + " not found in the array"); } } public static int linearSearch(int[] arr, int target) { for (int i = 0; i < arr.length; i++) { if (arr[i] == target) { return i; // Return the index where the element is found } } return -1; // Return -1 if the element is not found } }

Output:

mathematica
Element 23 found at index 4

In this example, the linearSearch function takes an array and a target element to be searched. It iterates through each element of the array and compares it with the target element. If a match is found, the function returns the index of the element. If no match is found after checking all elements, the function returns -1. In the given input array, the target element 23 is found at index 4.


Search
Related Articles

Leave a Comment: