5. [16 marks total Suppose you have an array S indexed from I to n which contains n numbers, not in any particalar order, and

5. [16 marks total Suppose you have an array S indexed from I to n which contains n numbers, not in any particalar order, and you wish to count how many times a given number x occurs in S. Consider the recursive algorithm below for this which finds the mumber of occurrences of x in the index range ij in S. Of course, solving the problem would involve an initial call to the algorithm for the range n int CountOccur (int int mid, count ifji return 0 else mid Floorl+2) if simid) x Count-1+CountOccurimid-1)+ CountOccur(mid+1,0 else Count CountOccurl,.mid-1) + CountOccur(mid+1, ); return Countt a) 12 marks Design a dynamic programming version of the above recursive algorithm and write the pseudocode for your algorithm For this algarithm, you shoald have a table which has an entry for every index pair i and i, 1 i n, 1 n. For index pair i ndjyour table should contain the number of times x appears in S in the range ..j. And of course, yoa must allow for the fact that you will need entries for ji sometimes too (so you may need to enlarge your table for this think sbout this) b) 3 marks llustrate your algorithm on the following example: s-(2,3,6, 2,7, 8, 2,9, x-2 [1 marks State the complexity of your algorithm, where you are counting the number of table entries calculated



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *