Linear search or sequential search is a method for finding a particular value in a list, that consists of checking every one of its elements, one at a time and in sequence, until the desired one is found. Linear search is the simplest search algorithm.
A simple approach is to do linear search, i.e
- Start from the leftmost element of arr[] and one by one compare x with each element of arr[]
- If x matches with an element, return the index.
- If x doesn’t match with any of elements, return -1.
class
LinearSearch
{
// This function returns index of element x in arr[]
static
int
search(
int
arr[],
int
n,
int
x)
{
for
(
int
i =
0
; i < n; i++)
{
// Return the index of the element if the element
// is found
if
(arr[i] == x)
return
i;
}
// return -1 if the element is not found
return
-
1
;
}
}
Java program for linear search: Linear search is very simple, To check if an element is present in the given list we compare search element with every element in the list. If the number is found then success occurs otherwise the list doesn't contain the element we are searching.
Java programming code
ANOTHER CODE ON LINEAR SEARCH
/* Program: Linear Search Example
* Written by: sambyte from sjavaspot.com
*/
import java.util.Scanner;
class LinearSearchExample
{
public static void main(String args[])
{
int counter, num, item, array[];
//To capture user input
Scanner input = new Scanner(System.in);
System.out.println("Enter number of elements:");
num = input.nextInt();
//Creating array to store the all the numbers
array = new int[num];
System.out.println("Enter " + num + " integers");
//Loop to store each numbers in array
for (counter = 0; counter < num; counter++)
array[counter] = input.nextInt();
System.out.println("Enter the search value:");
item = input.nextInt();
for (counter = 0; counter < num; counter++)
{
if (array[counter] == item)
{
System.out.println(item+" is present at location "+(counter+1));
/*Item is found so to stop the search and to come out of the
* loop use break statement.*/
break;
}
}
if (counter == num)
System.out.println(item + " doesn't exist in array.");
}
}
Output 1:
Enter number of elements:
6
Enter 6 integers
28
53
68
9
3
100
Enter the search value:
68
45 is present at location 3
Output 2:
Enter number of elements:
3
Enter 3 integers
11
200
40
Enter the search value:
97
97 doesn't exist in array.
No comments:
Post a Comment