Linear search in Java
Linear search in Java is a quite simple searching algorithm. In this kind of search, a sequential search is completed for all item one after the other. Each item is checked and if a match is found then that individual item is returned, in any other case the search continues till the last item of the list.Linear Search Algorithm:
- step 1: First you have to take an array input from user
- step 2: Also take an item input through user which you want to store after that store this item into a variable called number.
- Step 3: Start a loop and loop structure look like for(int i=0;i<arr.length;i++)
- Step 4: Traverse each element of the array one by one.
- Step 5: If item is found, return the index position of the element and print this using System.out.println();
- Step 6: If item is not found in the array print that there is no such element present in this array.
Example:
Input: [21,21,22,23,24,32]
Output: 32 found At index 6
Java program for Linear Search Algorithm
Code:
package datastructure;
import java.util.Scanner;
public class linears {
public static void
main(String[] args) {
Scanner
obj=new Scanner(System.in);
System.out.println("Enter
the length of array");
int
number=obj.nextInt();
int
arr[]=new int[number];
int i;
System.out.println("Enter
the element of array");
for(i=0;i&<number;i++)
{
arr[i]=obj.nextInt();
}
System.out.println("Eneter
the item which you want to search");
int
item=obj.nextInt();
System.out.println("applying linear search");
System.out.println("applying linear search");
for(i=0;i<number;i++)
{
if(item==arr[i])
{
System.out.println(item+"
found at index"+(i+1));
break;
}
}
if(i==number)
{
System.out.println("there
is no such element in the list");
}
}
}
Output:
Enter the length of array
6
Enter the element of array
21
21
22
23
24
32
Eneter the item which you want to search
32
applying linear search
applying linear search
32 found at index 6
Comments
Post a Comment
Please do not enter any spam link