August 14 2015

Linear search program in java

Linear search program in java

Linear search is used to find whether a given element is available in an array or not. It is also called as sequential search.

Algorithm

Compare the given element with each element of the array until the element is found or list ends.

Example


import java.util.Scanner;

public class LinearSearch {

 public static void main(String[] args) {

 int[] marks = { 10, 15, 8, 11, 19 };

 System.out.println("Linear search program in java");

 Scanner sc = new Scanner(System.in);

 System.out.println("Enter the number to search :");

 int number = sc.nextInt();
 int flag = 0;
 int position = 0;

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

 if (number == marks[i]) {
 position = i + 1;
 flag = 1;
 break;
 }

 }

 if (flag == 1) {
 System.out.println(number + " found in the array");
 System.out.println("Position : " + position);
 } else {
 System.out.println(number + " not found in the array");
 }

 }

}

Output

Linear search program in java
Enter the number to search :
11
11 found in the array
Position : 4

Linear search program in java
Enter the number to search :
100
100 not found in the array


Copyright © 2014. All rights reserved.

Posted August 14, 2015 by answersz in category Bluej Java Programs for ICSE Class 10 and 9 Practice, Core Java

1 thoughts on “Linear search program in java

Leave a Comment

Your email address will not be published. Required fields are marked *

*