This preview shows pages 1–3. Sign up to view the full content.
CS130B(Winter 2002) Assignment2 Solution Sketch
Question 1.
Algorithm
:
set counter=1, canditate=A[0];
for i=1 to n1 do
if counter==0
canditate=A[i];
counter=1;
else
if canditate==A[i]
counter++;
else
counter;
end if
end if
end for
counter=0
for i=0 to n1 do
if canditate==A[i]
counter++;
end if
end for
if counter>n/2
return canditate;
else
return null;
Complexity:
There are only two scans of the “n” elements. The complexity is O(n).
Alternative:
You can use a stack instead of counter and candidate. But it needs more space. Some
of students constructed a serial of array by keeping one element if two adjacent
elements are the same, and canceling both of them if they are different. By this way,
you can get one or two candidates finally, then check it.
Common Errors:
Some students build a big hash array with the elements of input array as its indices,
but this method only works for positive integers and of course potentially very large
wasted spaces.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document Question 2.
Algorithm:
for i:= 1 to n do
V
i1
={A
A>a is a production and the i
th
symbol of x is a }
End for;
For j:=2 to n do
For i:=1 to (nj+1) do
V
ij
:=null(i.e. empty set);
For k:= 1 to j1 do
V
ij
:=V
ij
U {A A>BC is a production, B is in V
ik
and C is in
This is the end of the preview. Sign up
to
access the rest of the document.
This note was uploaded on 05/20/2011 for the course CIS 6930 taught by Professor Staff during the Fall '08 term at University of Florida.
 Fall '08
 Staff
 Algorithms

Click to edit the document details