Tuesday, November 2, 2021

Programs for Linear Search

Programs to Linear Search

Programs for Linear Search

Linear Search algorithm searches an element in a list/array which is not necessarily to be sorted. The algorithm will search entire list/array from beginning to end for the matching.

The Pascal, Python and Java programs are given for the Linear Search as a function which returns true if the element is found or it returns false.

Pascal Program for Linear Search

program LSearch;

Function LinearSearch(X: Integer; arr: Array of Integer): boolean;
var
   found: boolean;
   L,R:integer;

begin
     found:=False;
     if  (Length(arr) = 0) then
         LinearSearch:= found
     else
     begin
          L:=0;
          R:=Length(arr) - 1;
          while ((found=False) and (L<=R)) do
          begin
               if  (X=arr[L]) then
                   found:=True;
               L:=L+1;
	  end;
          LinearSearch:= found;
     end;
end;
{main program}
var
  n: array [0..9] of integer;
  inp: boolean;
  num:integer;

begin
  n[0]:=12;
  n[1]:=15;
  n[2]:=20;
  n[3]:=27;
  n[4]:=29;
  n[5]:=30;
  n[6]:=78;
  n[7]:=81;
  n[8]:=89;
  n[9]:=95;
  write('Enter a number to search?');
  readln(num);
  inp:=LinearSearch(num,n);
  writeln(inp);
  readln;
end.

Python Program for Linear Search

def LinearSearch(X, arr):
    found=False
    if  (len(arr)==0):
        return found
    else:
        L=0
        R=len(arr)-1
        while ((found==False) and  (L<=R)):
            if  (X==arr[L]):
                found=True
            L=L+1
        return found;		
#main program
AA=[20,30,4,7,8,20,100,150]
num=int(input("Enter a number?"))
F=LinearSearch(num,AA)
print("The number " ,num, "  found is : ", F)

Java program for Linear Search

import java.util.Scanner;
public class LinearSearch
{
	public boolean Search(int X, int[] arr)
	{
		boolean found;
		int L,R;	
		found=false;	
		if  ((arr.length)==0)
			return found;
		else
		{
			L=0;
			R=arr.length - 1;
			while ((found==false) && (L<=R))
			{
				if  (X==arr[L])
					found=true;
				L=L+1;	
			}
			return found;		
		}
	}
	//main
	public static void main(String arg[])
	{
		int[] AA;
		AA=new int[10];
		int num;
		boolean f;
		AA[0]=10;
		AA[1]=5;
		AA[2]=30;
		AA[3]=20;
		AA[4]=15;
		AA[5]=22;
		AA[6]=11;
		AA[7]=12;
		AA[8]=3;
		AA[9]=50;
		System.out.println("Enter a number to Search?");
		Scanner sc=new Scanner(System.in);
		num=sc.nextInt();
		LinearSearch LS= new LinearSearch();
		f=LS.Search(num,AA);
		System.out.println(f);		
	}
}


No comments:

Post a Comment