Monday, October 22, 2012

Linear Search in Java

Below is simple program in java which shows the linear search.


import java.io.*;

class LinearSearch
{
  int ar[];
  int ele,n;

  public void setData() throws Exception
  {
     ar = new int[10];
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the size for array : ");    
    n = Integer.parseInt(br.readLine());

    System.out.println("Enter the data for array : ");    
    for(int i = 0 ; i < n ; i++)
    {
      ar[i] = Integer.parseInt(br.readLine());
    }
    
    System.out.println("Enter the data to be searched : ");
    ele = Integer.parseInt(br.readLine());
  }

  public void putData()
  {
    System.out.println("The array is : ");
    for(int i = 0 ; i < n ; i++)
    {
      System.out.println(" " + ar[i]);
    }
  }

  public void LinSrch()
  {
    int i;
   
    for(i = 0 ; i < n ; i++)
    {
      if(ar[i] == ele)
      {
        break;
      }
    }
    if(i == ar.length)
    {
      System.out.println("\nElement not found");
    }
    else
    {
      System.out.println("\nElement found at " + i);
    }
  }

  public static void main(String args[]) throws Exception
  {
    LinearSearch ln = new LinearSearch();
    ln.setData();
    ln.putData();
    ln.LinSrch();
  }

}

No comments:

Post a Comment

MS SQL : How to identify fragmentation in your indexes?

Almost all of us know what fragmentation in SQL indexes are and how it can affect the performance. For those who are new Index fragmentation...