Tuesday, 6 January 2015

Java Program to search an element using Linear Search



In this post we will discuss on a basic searching technique called as linear search . It searches an element (generally called a key ) from an array. Unlike binary search , the array need not to be sorted.
This Linear Search technique generally compares each and every element with the key , if both matches , the algorithm returns that element is found and its position.



PROGRAM :
package codingcorner.in;

import java.util.Scanner;

public class LinearSearch {
 public static void main(String[] args) {
  int key, i, n;
  int[] array = new int[100];
  Scanner scan = new Scanner(System.in);
  System.out.print("How many elements? \t");
  n = scan.nextInt();

  for (i = 0; i < n; i++) {
   System.out.print("Enter number" + (i + 1) + ":\t");
   array[i] = scan.nextInt();
  }

  System.out.print("\nEnter the number to search:\t");
  key = scan.nextInt();
  scan.close();
  for (i = 0; i < n; i++) {
   if (array[i] == key) {
    System.out.println(key + " is present at position " + (i + 1));
    break;
   }
  }
  if (i == n)
   System.out.println(key + " is not present in array.");
 }
}


OUTPUT :