Hw2soln - CS130B(Winter 2002 Assignment2 Solution Sketch Question 1 Algorithm set counter=1 canditate=A[0 for i=1 to n-1 do if counter=0

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
CS130B(Winter 2002)- Assignment2 Solution Sketch Question 1. Algorithm : set counter=1, canditate=A[0]; for i=1 to n-1 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 n-1 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.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
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 (n-j+1) do V ij :=null(i.e. empty set); For k:= 1 to j-1 do V ij :=V ij U {A| A->BC is a production, B is in V ik and C is in
Background image of page 2
Image of page 3
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.

Page1 / 3

Hw2soln - CS130B(Winter 2002 Assignment2 Solution Sketch Question 1 Algorithm set counter=1 canditate=A[0 for i=1 to n-1 do if counter=0

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online