Wednesday, 1 March 2017

Java Program For Linear Search

Linear Search is a search method, in which the way to be searched is contrasted and every component in the rundown until it is found. This strategy works regardless of the possibility that the rundown is not sorted. It is thought to be slower than double hunt as the measure of the information (list) develops. Java Program For Linear Search


Here is the code for Linear Search in java/Java Program For Linear Search


import java.io.*;
class LinearSearch{
public static void main(String args[])throws IOException{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int a[]={92, 34, 78, 12, 45, 7, 81, 60, 51, 10};
int key, i;
System.out.print("Enter the integer to search:");
key=Integer.parseInt(br.readLine());
for(i=0;i<a.length;i++){
if(key==a[i])
break;
}
if(i==10)
System.out.println(key+" not found");
else
System.out.println(key+" found at index "+i);
}
}

Another Program For Linear Search/Java Program For Linear Search

import java.io.*;

public class LinearSearch
{
  public static void main(String args[]) throws Exception
  {
    int values[] = {5, 16, 10, 17, 8, 25};
    int key;
    int i;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Array values are:");
    for(int n:values)
    {
      System.out.print(n+"\t");
    }
    System.out.println("\nPlease enter a key (search) value:");
    key = Integer.parseInt(br.readLine());
    for(i=0; i< values.length; i++)
    {
      if(values[i] == key)
      {
        break;
      }
    }
    if(i==values.length)
    {
      System.out.println(key+" not found...!");
    }
    else
    {
      System.out.println(key+" found at position "+(i+1));
    }
  }

}


Java Program to Search an Element in an Array using Linear Search/Java Program For Linear Search


package com.tcc.java.programs;

import java.util.*;

public class ArrayLinearSearch {
    public static void main(String args[]) {
        int count, num, i;
        int[] inputArray = new int[500];
 
        Scanner in = new Scanner(System.in);
 
        System.out.println("Enter number of elements");
        count = in.nextInt();
        System.out.println("Enter " + count + " elements");
        for(i = 0; i < count; i++) {
            inputArray[i] = in.nextInt();
        }

        System.out.println("Enter element to search");
        num = in.nextInt();
        // Compare each element of array with num
        for (i = 0; i < count ; i++) {
            if(num == inputArray[i]){
               System.out.println(num+" is present at index "+i);
               break;
            }
        }
 
        if(i == count)
           System.out.println(num + " not present in input array");
    }
}

If you like this program Java Program For Linear Search do a comment and let us know

0 comments:

Post a Comment