Home      Affiliated Colleges      Course content      First Sem     Second Sem     Third Sem     Fourth Sem     Fifth Sem     Sixth Sem     Seventh Sem     Eighth Sem     Lab report 4th sem     Contact    

Monday, August 9, 2010

Design analysis and algorithm Program 2


 

2.     Consider the searching problem where:

 Input: A sequence of n numbers A = <a1, a2, …, an> and a value v.
 Output: An index i such that v=A[i] or the special value NIL if v doesn't appear in A. Write pseudo code for linear search and implement by using any programming language, which scans through the sequence, looking for v.

Soln:
Pseudocode:
1.      Input the Numbers in an array . Let the numbers in array is A.
2.      Input the value V.
3.      let c=0
4.      for( i=1;i<=n;i++)
{
            If(A[i]==V)
            {
                        Print(The Number is found at i);
                        c=1;
                        Break;
            }
}
If(c==0)
{
            Print("The Number is not found in the array");
            Print(" So the Value is NIL");
                                    }
5.      End of Program.

Linear search(A):             
cost      times
a.       for i = 0 to n-1                    C1        n
b.      if V = = A[i]                       C2        (n-1)
c.             return i                          C3        1
d.      return -1                             C4        1

Time complexity:
Worst case:
T(n)      = C1* n + C2 * (n-1) + C3 + C4
= (C1+C2) * n - (C2-C3-C4)
= a*n – b         (where a = (C1+C2), b = (C2-C3-C4) )
= O(n)
Best case:-
T(n)      = Ω(1)

Average case:-
T(n)      = (n+1) / 2


No comments:

Post a Comment

^ Scroll to Top Related Posts with Thumbnails ^ Go to Top