|
|
Subject:
Data Structure and Algorithm in Java
Category: Computers > Programming Asked by: math01-ga List Price: $20.00 |
Posted:
18 May 2003 12:05 PDT
Expires: 19 May 2003 01:53 PDT Question ID: 205492 |
The solution I am seeking is for question 3. Questions 1 and 2 are just to help you understand the problem. 1. Consider the following program for computing the cumulative sum of a given list. An example of sample input and output from this program is as follows: Input list: 1 4 2 6 7 1 0 5 Output list: 1 5 7 13 20 21 21 26 Note that each number in the output list is the sum of all numbers up to (and including) the current location in the input list. Our first program segment for computing this is as follows: for (i = 0; i < n; i++) output_list[i] = 0; for (i = 0; i < n; i++) for (j = 0; j <= i; j++) output_list[i] += input_list[j]; What is the runtime of this code segment in big-O notation? 2. We write an alternate program for the same problem. In this case, we notice that to compute output_list[i], you only need to add input_list[i] and output_list[i-1]. The program segment is as follows: for (i = 0; i < n; i++) output_list[i] = 0; output_list[0] = input_list[0]; for (i = 1; i < n; i++) output_list[i] = output_list[i-1] + input_list[i]; What is the runtime of this code segment in big-O notation? 3. Code the programs for computing cumulative sum of a list (illustrated in Problems 1 and 2) in Java. Execute each of these programs on lists of increasing sizes and note the runtime. Comment on the growth rate of runtimes for the two programs |
|
There is no answer at this time. |
|
Subject:
Re: Data Structure and Algorithm in Java
From: ranavikas-ga on 18 May 2003 22:34 PDT |
Hmmm. That looks like a kinda homework problem ;) Anyway, I won't code it, but can give the runtimes. Runtime of first code is O(n^2). Its always easy to calculate the runtime from a given code - you have two loops of O(n) each. More specifically, the number of times the line no. 5 will be executed is 1 + 2 + .... + n = n*(n+1)/2 = O(n^2). Runtime of second code is O(n). (Try yourselves on above lines.) BTW, just as an advice, it will benefit you a lot if you try to calculate runtimes of similar problems on your own. |
If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you. |
Search Google Answers for |
Google Home - Answers FAQ - Terms of Service - Privacy Policy |