Wednesday, June 17, 2015

Linear search algorithm for CSE students


Linear search algorithm
Here DATA is an array with N elements and ITEM is to search from the array using linear search algorithm.

1. Repeat for J=0 to N-1
       if (ITEM==DATA[ J ]) then
          Set K=J+1;
          Print item found at position K
          Set FLAG=1;
       end of if
   end of for-loop
2. if (FLAG==0) then
      print item not found

Example 1.1
Let consider an array DATA[ ] where 3, 33, 1, 7 & 3 is stored, so N will be 5 in this case. If ITEM is 3, then find out 3 from the array using linear search algorithm.

Iteration
J=0, N=5, ITEM=3, FLAG=0, K=0

Step 01
for(j=0; j<N; j++)
as j=0 & n=5, so the condition j<n is true
   if (ITEM==DATA[ J ])
   as item=3 and data[0]=3, so the condition item==data[j] is true
      k=0+1=1
      print 'item is found at position 1'
      flag=1
if(flag==0)
as flag=1 now, so the condition is false

Step 02
j=1, n=3, k=1, flag=1

for(j=0; j<N; j++)
as j=1 & n=5, so the condition j<n is true
   if (ITEM==DATA[ J ])
   as item=3 and data[1]=33, so the condition item==data[j] is false
     
if(flag==0)
as flag=1 now, so the condition is false

Step 03
j=2, n=3, k=1, flag=1

for(j=0; j<N; j++)
as j=2 & n=5, so the condition j<n is true
   if (ITEM==DATA[ J ])
   as item=3 and data[2]=1, so the condition item==data[j] is false
     
if(flag==0)
as flag=1 now, so the condition is false

Step 04
j=3, n=3, k=1, flag=1

for(j=0; j<N; j++)
as j=3 & n=5, so the condition j<n is true
   if (ITEM==DATA[ J ])
   as item=3 and data[3]=7, so the condition item==data[j] is false
     
if(flag==0)
as flag=1 now, so the condition is false

Step 05
j=4, n=3, k=1, flag=1

for(j=0; j<N; j++)
as j=4 & n=5, so the condition j<n is true
   if (ITEM==DATA[ J ])
   as item=3 and data[4]=3, so the condition item==data[j] is true
      k=4+1=5
      print 'item is found at position 5'
      flag=1
     
if(flag==0)
as flag=1 now, so the condition is false

Step 06
j=5, n=3, k=1, flag=1

for(j=0; j<N; j++)
as j=5 & n=5, so the condition j<n is false
   exit for loop
     
if(flag==0)
as flag=1 now, so the condition is false

Recommended posts...

Advertisement


No comments:

Post a Comment