SlideShare a Scribd company logo
1 of 6
Download to read offline
In three of the exercises below there is given a code of a method named find, and a fourth one
named printMany. Analyze the codes through the following points.
Explain your choice of the input size n and in terms of O(n) scale determine the running time
(number of steps) T(n) of the algorithms represented by the methods.
Use the simplest and possibly the smallest valid Big-Oh expression.
T(n) can also be considered as the number elementary operations the algorithm must make.
If it applies, point out your estimates for the worst and best cases, and also for the average case
performance if available.
Document each method describing what you consider the method’s precondition and post-
condition.
It is not necessary to run these methods in actual programs, but if the task it performs is dubious,
testing the method with various input in actual applications of the code may help to find its
purpose and the big-Oh estimate.
1) int find( int[] list, int element ){
int answer = 0;
for(int k = 0; k < list.length; k++ )
if (element==list[k])
answer++;
return answer;
}//end method
Comments
What does the method do:
Input size n =
Worst case T(n) = O(________) Best case T(n) = O(________)
2) staticintfind(int[] arr){
zeroCounter = 0;
(intk = 0; k< arr.length; k++){
(arr[k]==0)
zeroCounter++;
}
(zeroCounter==arr.length)
0;
(zeroCounter < arr.length - 2){
//see maxIndex() definition below
max = maxIndex(arr);
arr[max] = 0;
//see display() definition below
display(arr);
zeroCounter ++;
}
maxIndex(arr);
//end method
//helper methods
3) staticint maxIndex(int[]arr){
int maxindex = 0;
for(int k = 0 ; k< arr.length; k++){
// note the use of absolute value
if(Math.abs(arr[maxindex]) < Math.abs(arr[k]))
maxindex = k;
}
return maxindex;
}
staticvoid display(int[]arr){
System.out.println();
for(int k = 0 ; k< arr.length; k++)
System.out.print(arr[k]+” “);
System.out.println();
}
Comments
What does the method do:
Input size n =
Worst case T(n) = O(________) Best case T(n) = O(________)
3) int find(int[] num){
int answer = 0;
for(int k = 0; k < num.length; k++ )
for(int j = k; j< num.length; j++){
int current = 0;
for(int i = k; i<=j; i++)
current += num[i];
if (current > answer)
answer = current;
}
return answer;
}
Note: Given two indices i<=j of an array of integers num, the sum
num[i]+ num[i+1] + …+ num[j] is called a sub-sum
Comments
What does the method do:
Input size n =
Worst case T(n) = O(________) Best case T(n) = O(________)
4) void printMany(int[]arr){
int N = arr.length;
for(int k = 0 ; k< N; k++){
int p = k;
while(p>0){
System.out.println(arr[p]+" ");
p = p/2;
}
}
Comments
What does the method do:
Input size n =
Worst case T(n) = O(________) Best case T(n) = O(________)
Solution
1) int find( int[] list, int element ){
int answer = 0;
for(int k = 0; k < list.length; k++ ) //traversing array start to end
if (element==list[k]) //checking for element
answer++; // if element found, increase by 1
return answer;
}//end method
In the function given above, we can see an array ‘list’, and an integer ‘element’ being accepted
as parameters.
We initialize an integer ‘answer’, with an initial value of 0.
What we are doing with this function is searching for the frequency of an element, in the list.
The for loop starts at index 0, and goes on till the end of the array. At each iteration, the if
statement checks whether the ‘element’ input by the user, is present in the list at the ‘kth’
position. Every time the element matches with the element present in the list, the value of
‘answer is incremented by 1.
When the loop terminates, after having traversed the entire array, the variable ‘answer’ has a
value stored, which is equal to the number of times the element input by the user, was found in
the list.
Hence, we get the frequency of the occurrence of an element in a list through this function.
Note: This is a classic example of ‘Linear search’ for an element, where we search the entire list
for an element.
It has a complexity T(n)= O(n) for Both Worst Case, and Best Case.
2) code not clear.
3)
3) int find(int[] num){
int answer = 0;
for(int k = 0; k < num.length; k++ ) //will traverse entire list
for(int j = k; j< num.length; j++){
int current = 0;
for(int i = k; i<=j; i++) // will traverse from k to j every time
current += num[i];
if (current > answer)
answer = current; // computing largest sub sum of list
}
return answer; //returning largest sub sum of list
}
On inspection, we can see that for k=0, and j=0, the i loop runs one time, and for k=0,j=1, the i
loop runs twice, and so on. Therefore, we can say that the inner most loop is bound between the
‘k’ loop and the ‘j’ loop, ‘k’ being the lower bound, and ‘j’ being the upper bound.
The inner most loop, bound between the values of k and j, calculates the sum of the elements
ranging from k to j (the sub-sum). If this sum is found to be greater than the previously computed
sub sum, then the answer is updated.
The ultimate motive of this method is to find the largest sub sum of the given list.
Let num.length() be n,
Then the outmost loop runs n times.
The second loop runs a total of n times when k=0, n-1 times when k=1, n-2 times for k=3 and so
on, running for a total of n(n+1)/2 times (sum of numbers of 1-n;
The third loop runs 1 time for k=0,j=0, 2 times for k=0,j=1 and so on.
Therefore the complexity of this method is given by O(n^3).
T(n)=O(n^3) (both worst and best cases).
4) void printMany(int[]arr){
int N = arr.length;
for(int k = 0 ; k< N; k++){
int p = k;
while(p>0){
System.out.println(arr[p]+" ");
p = p/2;
}
}
In this function, the outer k loop runs from 0 to N i.e. the entire list.
For k=0, p-0, and hence the inner while loop does not run.
For k=1, p=1, and hence the inner while loop runs 1 time, and prints 1 element.
For k=2, p=2 and hence the inner while loop runs twice, and prints two elements.
For k=3, p=3 and hence the inner while loop runs twice, and prints two elements.
For k=4, p=4 and hence the inner while loop runs thrice, and prints three elements.
For k=5, p=5 and hence the inner while loop runs thrice, and prints three elements.
And so on,
On further inspection, we find that the inner while loop runs and prints twice the number of
elements, it has printed for a certain number of iterations of the outer loop i.e. the inner loop first
runs 0 times, then it runs one time, then it runs two times, then it runs four times, and so on, or in
other words the number of elements printed is growing in multiples of two.
Analysis:
The outer loop runs N times. The inner loop runs 1+2+4… times, i.e. in a geometric progression
with common ratio of 2. The formula for sum of a GP is
S=a({r^n}-1)/(r-1)
Where r is the common ratio, a the first term.
The complexity can then be represented as
T(N)= O(n2^n) (both worst and best case).

More Related Content

Similar to In three of the exercises below there is given a code of a method na.pdf

Beginning direct3d gameprogrammingmath02_logarithm_20160324_jintaeks
Beginning direct3d gameprogrammingmath02_logarithm_20160324_jintaeksBeginning direct3d gameprogrammingmath02_logarithm_20160324_jintaeks
Beginning direct3d gameprogrammingmath02_logarithm_20160324_jintaeksJinTaek Seo
 
UNIT I- Session 3.pptx
UNIT I- Session 3.pptxUNIT I- Session 3.pptx
UNIT I- Session 3.pptxabcdefgh690537
 
Algorithm, Pseudocode and Flowcharting in C++
Algorithm, Pseudocode and Flowcharting in C++Algorithm, Pseudocode and Flowcharting in C++
Algorithm, Pseudocode and Flowcharting in C++Johnny Jean Tigas
 
Introducción al Análisis y diseño de algoritmos
Introducción al Análisis y diseño de algoritmosIntroducción al Análisis y diseño de algoritmos
Introducción al Análisis y diseño de algoritmosluzenith_g
 
Chp-1 Quick Review of basic concepts.pdf
Chp-1 Quick Review of basic concepts.pdfChp-1 Quick Review of basic concepts.pdf
Chp-1 Quick Review of basic concepts.pdfSolomonMolla4
 
Chapter-3-Sample-Space-of-Experiment.pdf
Chapter-3-Sample-Space-of-Experiment.pdfChapter-3-Sample-Space-of-Experiment.pdf
Chapter-3-Sample-Space-of-Experiment.pdfJuliusBoitizon
 
DSA Complexity.pptx What is Complexity Analysis? What is the need for Compl...
DSA Complexity.pptx   What is Complexity Analysis? What is the need for Compl...DSA Complexity.pptx   What is Complexity Analysis? What is the need for Compl...
DSA Complexity.pptx What is Complexity Analysis? What is the need for Compl...2022cspaawan12556
 
pradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqpradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqPradeep Bisht
 

Similar to In three of the exercises below there is given a code of a method na.pdf (20)

Beginning direct3d gameprogrammingmath02_logarithm_20160324_jintaeks
Beginning direct3d gameprogrammingmath02_logarithm_20160324_jintaeksBeginning direct3d gameprogrammingmath02_logarithm_20160324_jintaeks
Beginning direct3d gameprogrammingmath02_logarithm_20160324_jintaeks
 
Slide2
Slide2Slide2
Slide2
 
UNIT I- Session 3.pptx
UNIT I- Session 3.pptxUNIT I- Session 3.pptx
UNIT I- Session 3.pptx
 
21-algorithms.ppt
21-algorithms.ppt21-algorithms.ppt
21-algorithms.ppt
 
Algorithm, Pseudocode and Flowcharting in C++
Algorithm, Pseudocode and Flowcharting in C++Algorithm, Pseudocode and Flowcharting in C++
Algorithm, Pseudocode and Flowcharting in C++
 
Alg1
Alg1Alg1
Alg1
 
21-algorithms (1).ppt
21-algorithms (1).ppt21-algorithms (1).ppt
21-algorithms (1).ppt
 
Sorting
SortingSorting
Sorting
 
Lect-2.pptx
Lect-2.pptxLect-2.pptx
Lect-2.pptx
 
Introducción al Análisis y diseño de algoritmos
Introducción al Análisis y diseño de algoritmosIntroducción al Análisis y diseño de algoritmos
Introducción al Análisis y diseño de algoritmos
 
Anu DAA i1t unit
Anu DAA i1t unitAnu DAA i1t unit
Anu DAA i1t unit
 
Chp-1 Quick Review of basic concepts.pdf
Chp-1 Quick Review of basic concepts.pdfChp-1 Quick Review of basic concepts.pdf
Chp-1 Quick Review of basic concepts.pdf
 
Chapter-3-Sample-Space-of-Experiment.pdf
Chapter-3-Sample-Space-of-Experiment.pdfChapter-3-Sample-Space-of-Experiment.pdf
Chapter-3-Sample-Space-of-Experiment.pdf
 
Python_Module_2.pdf
Python_Module_2.pdfPython_Module_2.pdf
Python_Module_2.pdf
 
Q
QQ
Q
 
DSA Complexity.pptx What is Complexity Analysis? What is the need for Compl...
DSA Complexity.pptx   What is Complexity Analysis? What is the need for Compl...DSA Complexity.pptx   What is Complexity Analysis? What is the need for Compl...
DSA Complexity.pptx What is Complexity Analysis? What is the need for Compl...
 
13 Amortized Analysis
13 Amortized Analysis13 Amortized Analysis
13 Amortized Analysis
 
pradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqpradeepbishtLecture13 div conq
pradeepbishtLecture13 div conq
 
Daa chapter5
Daa chapter5Daa chapter5
Daa chapter5
 
Big o
Big oBig o
Big o
 

More from feelinggift

A) Which of the following element is seen in all organic molecules Si.pdf
A) Which of the following element is seen in all organic molecules Si.pdfA) Which of the following element is seen in all organic molecules Si.pdf
A) Which of the following element is seen in all organic molecules Si.pdffeelinggift
 
Given an ArrayList, write a Java method that returns a new ArrayList.pdf
Given an ArrayList, write a Java method that returns a new ArrayList.pdfGiven an ArrayList, write a Java method that returns a new ArrayList.pdf
Given an ArrayList, write a Java method that returns a new ArrayList.pdffeelinggift
 
Write an MSP430g2553 C program to drive a continually scrolling mess.pdf
Write an MSP430g2553 C program to drive a continually scrolling mess.pdfWrite an MSP430g2553 C program to drive a continually scrolling mess.pdf
Write an MSP430g2553 C program to drive a continually scrolling mess.pdffeelinggift
 
Which of the following is NOT a financial measurement needed to see .pdf
Which of the following is NOT a financial measurement needed to see .pdfWhich of the following is NOT a financial measurement needed to see .pdf
Which of the following is NOT a financial measurement needed to see .pdffeelinggift
 
Which process uses chemiosmosis A. Pyruvate oxidation B. Electron .pdf
Which process uses chemiosmosis  A. Pyruvate oxidation  B. Electron .pdfWhich process uses chemiosmosis  A. Pyruvate oxidation  B. Electron .pdf
Which process uses chemiosmosis A. Pyruvate oxidation B. Electron .pdffeelinggift
 
What motives do corporate executives have that force them to embrace.pdf
What motives do corporate executives have that force them to embrace.pdfWhat motives do corporate executives have that force them to embrace.pdf
What motives do corporate executives have that force them to embrace.pdffeelinggift
 
when are business cases or project charters overkillSolutionP.pdf
when are business cases or project charters overkillSolutionP.pdfwhen are business cases or project charters overkillSolutionP.pdf
when are business cases or project charters overkillSolutionP.pdffeelinggift
 
True or False The Congressional Budget Office projects that approxi.pdf
True or False The Congressional Budget Office projects that approxi.pdfTrue or False The Congressional Budget Office projects that approxi.pdf
True or False The Congressional Budget Office projects that approxi.pdffeelinggift
 
Using the space provided compose an ESSAY concerning the following qu.pdf
Using the space provided compose an ESSAY concerning the following qu.pdfUsing the space provided compose an ESSAY concerning the following qu.pdf
Using the space provided compose an ESSAY concerning the following qu.pdffeelinggift
 
We continually hear about interest groups in the news. Understanding.pdf
We continually hear about interest groups in the news. Understanding.pdfWe continually hear about interest groups in the news. Understanding.pdf
We continually hear about interest groups in the news. Understanding.pdffeelinggift
 
View transaction list Journal entry worksheet 6 9 The company receive.pdf
View transaction list Journal entry worksheet 6 9 The company receive.pdfView transaction list Journal entry worksheet 6 9 The company receive.pdf
View transaction list Journal entry worksheet 6 9 The company receive.pdffeelinggift
 
Physical security is a fundamental component of any secure infrastru.pdf
Physical security is a fundamental component of any secure infrastru.pdfPhysical security is a fundamental component of any secure infrastru.pdf
Physical security is a fundamental component of any secure infrastru.pdffeelinggift
 
TrueFalse Verilog is case-insensitive TF Verilog has constructs.pdf
TrueFalse Verilog is case-insensitive TF Verilog has constructs.pdfTrueFalse Verilog is case-insensitive TF Verilog has constructs.pdf
TrueFalse Verilog is case-insensitive TF Verilog has constructs.pdffeelinggift
 
This is a homework assignment that I have for my Java coding class. .pdf
This is a homework assignment that I have for my Java coding class. .pdfThis is a homework assignment that I have for my Java coding class. .pdf
This is a homework assignment that I have for my Java coding class. .pdffeelinggift
 
The Jannuschs operated Festival Foods, a busi- ness that served conc.pdf
The Jannuschs operated Festival Foods, a busi- ness that served conc.pdfThe Jannuschs operated Festival Foods, a busi- ness that served conc.pdf
The Jannuschs operated Festival Foods, a busi- ness that served conc.pdffeelinggift
 
The first thermodynamic law for a system of charged molecules in elec.pdf
The first thermodynamic law for a system of charged molecules in elec.pdfThe first thermodynamic law for a system of charged molecules in elec.pdf
The first thermodynamic law for a system of charged molecules in elec.pdffeelinggift
 
show all of your work to arrive a final result Simple Interest Simpl.pdf
show all of your work to arrive a final result Simple Interest Simpl.pdfshow all of your work to arrive a final result Simple Interest Simpl.pdf
show all of your work to arrive a final result Simple Interest Simpl.pdffeelinggift
 
Terms from which students can chooseMacrophages; •Only one.pdf
Terms from which students can chooseMacrophages; •Only one.pdfTerms from which students can chooseMacrophages; •Only one.pdf
Terms from which students can chooseMacrophages; •Only one.pdffeelinggift
 
Simulate the Stakeholder deliverable for the development of an onlin.pdf
Simulate the Stakeholder deliverable for the development of an onlin.pdfSimulate the Stakeholder deliverable for the development of an onlin.pdf
Simulate the Stakeholder deliverable for the development of an onlin.pdffeelinggift
 
I want to write this program in java.Write a simple airline ticket.pdf
I want to write this program in java.Write a simple airline ticket.pdfI want to write this program in java.Write a simple airline ticket.pdf
I want to write this program in java.Write a simple airline ticket.pdffeelinggift
 

More from feelinggift (20)

A) Which of the following element is seen in all organic molecules Si.pdf
A) Which of the following element is seen in all organic molecules Si.pdfA) Which of the following element is seen in all organic molecules Si.pdf
A) Which of the following element is seen in all organic molecules Si.pdf
 
Given an ArrayList, write a Java method that returns a new ArrayList.pdf
Given an ArrayList, write a Java method that returns a new ArrayList.pdfGiven an ArrayList, write a Java method that returns a new ArrayList.pdf
Given an ArrayList, write a Java method that returns a new ArrayList.pdf
 
Write an MSP430g2553 C program to drive a continually scrolling mess.pdf
Write an MSP430g2553 C program to drive a continually scrolling mess.pdfWrite an MSP430g2553 C program to drive a continually scrolling mess.pdf
Write an MSP430g2553 C program to drive a continually scrolling mess.pdf
 
Which of the following is NOT a financial measurement needed to see .pdf
Which of the following is NOT a financial measurement needed to see .pdfWhich of the following is NOT a financial measurement needed to see .pdf
Which of the following is NOT a financial measurement needed to see .pdf
 
Which process uses chemiosmosis A. Pyruvate oxidation B. Electron .pdf
Which process uses chemiosmosis  A. Pyruvate oxidation  B. Electron .pdfWhich process uses chemiosmosis  A. Pyruvate oxidation  B. Electron .pdf
Which process uses chemiosmosis A. Pyruvate oxidation B. Electron .pdf
 
What motives do corporate executives have that force them to embrace.pdf
What motives do corporate executives have that force them to embrace.pdfWhat motives do corporate executives have that force them to embrace.pdf
What motives do corporate executives have that force them to embrace.pdf
 
when are business cases or project charters overkillSolutionP.pdf
when are business cases or project charters overkillSolutionP.pdfwhen are business cases or project charters overkillSolutionP.pdf
when are business cases or project charters overkillSolutionP.pdf
 
True or False The Congressional Budget Office projects that approxi.pdf
True or False The Congressional Budget Office projects that approxi.pdfTrue or False The Congressional Budget Office projects that approxi.pdf
True or False The Congressional Budget Office projects that approxi.pdf
 
Using the space provided compose an ESSAY concerning the following qu.pdf
Using the space provided compose an ESSAY concerning the following qu.pdfUsing the space provided compose an ESSAY concerning the following qu.pdf
Using the space provided compose an ESSAY concerning the following qu.pdf
 
We continually hear about interest groups in the news. Understanding.pdf
We continually hear about interest groups in the news. Understanding.pdfWe continually hear about interest groups in the news. Understanding.pdf
We continually hear about interest groups in the news. Understanding.pdf
 
View transaction list Journal entry worksheet 6 9 The company receive.pdf
View transaction list Journal entry worksheet 6 9 The company receive.pdfView transaction list Journal entry worksheet 6 9 The company receive.pdf
View transaction list Journal entry worksheet 6 9 The company receive.pdf
 
Physical security is a fundamental component of any secure infrastru.pdf
Physical security is a fundamental component of any secure infrastru.pdfPhysical security is a fundamental component of any secure infrastru.pdf
Physical security is a fundamental component of any secure infrastru.pdf
 
TrueFalse Verilog is case-insensitive TF Verilog has constructs.pdf
TrueFalse Verilog is case-insensitive TF Verilog has constructs.pdfTrueFalse Verilog is case-insensitive TF Verilog has constructs.pdf
TrueFalse Verilog is case-insensitive TF Verilog has constructs.pdf
 
This is a homework assignment that I have for my Java coding class. .pdf
This is a homework assignment that I have for my Java coding class. .pdfThis is a homework assignment that I have for my Java coding class. .pdf
This is a homework assignment that I have for my Java coding class. .pdf
 
The Jannuschs operated Festival Foods, a busi- ness that served conc.pdf
The Jannuschs operated Festival Foods, a busi- ness that served conc.pdfThe Jannuschs operated Festival Foods, a busi- ness that served conc.pdf
The Jannuschs operated Festival Foods, a busi- ness that served conc.pdf
 
The first thermodynamic law for a system of charged molecules in elec.pdf
The first thermodynamic law for a system of charged molecules in elec.pdfThe first thermodynamic law for a system of charged molecules in elec.pdf
The first thermodynamic law for a system of charged molecules in elec.pdf
 
show all of your work to arrive a final result Simple Interest Simpl.pdf
show all of your work to arrive a final result Simple Interest Simpl.pdfshow all of your work to arrive a final result Simple Interest Simpl.pdf
show all of your work to arrive a final result Simple Interest Simpl.pdf
 
Terms from which students can chooseMacrophages; •Only one.pdf
Terms from which students can chooseMacrophages; •Only one.pdfTerms from which students can chooseMacrophages; •Only one.pdf
Terms from which students can chooseMacrophages; •Only one.pdf
 
Simulate the Stakeholder deliverable for the development of an onlin.pdf
Simulate the Stakeholder deliverable for the development of an onlin.pdfSimulate the Stakeholder deliverable for the development of an onlin.pdf
Simulate the Stakeholder deliverable for the development of an onlin.pdf
 
I want to write this program in java.Write a simple airline ticket.pdf
I want to write this program in java.Write a simple airline ticket.pdfI want to write this program in java.Write a simple airline ticket.pdf
I want to write this program in java.Write a simple airline ticket.pdf
 

Recently uploaded

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 

Recently uploaded (20)

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 

In three of the exercises below there is given a code of a method na.pdf

  • 1. In three of the exercises below there is given a code of a method named find, and a fourth one named printMany. Analyze the codes through the following points. Explain your choice of the input size n and in terms of O(n) scale determine the running time (number of steps) T(n) of the algorithms represented by the methods. Use the simplest and possibly the smallest valid Big-Oh expression. T(n) can also be considered as the number elementary operations the algorithm must make. If it applies, point out your estimates for the worst and best cases, and also for the average case performance if available. Document each method describing what you consider the method’s precondition and post- condition. It is not necessary to run these methods in actual programs, but if the task it performs is dubious, testing the method with various input in actual applications of the code may help to find its purpose and the big-Oh estimate. 1) int find( int[] list, int element ){ int answer = 0; for(int k = 0; k < list.length; k++ ) if (element==list[k]) answer++; return answer; }//end method Comments What does the method do: Input size n = Worst case T(n) = O(________) Best case T(n) = O(________) 2) staticintfind(int[] arr){ zeroCounter = 0; (intk = 0; k< arr.length; k++){ (arr[k]==0) zeroCounter++; } (zeroCounter==arr.length) 0; (zeroCounter < arr.length - 2){ //see maxIndex() definition below
  • 2. max = maxIndex(arr); arr[max] = 0; //see display() definition below display(arr); zeroCounter ++; } maxIndex(arr); //end method //helper methods 3) staticint maxIndex(int[]arr){ int maxindex = 0; for(int k = 0 ; k< arr.length; k++){ // note the use of absolute value if(Math.abs(arr[maxindex]) < Math.abs(arr[k])) maxindex = k; } return maxindex; } staticvoid display(int[]arr){ System.out.println(); for(int k = 0 ; k< arr.length; k++) System.out.print(arr[k]+” “); System.out.println(); } Comments What does the method do: Input size n = Worst case T(n) = O(________) Best case T(n) = O(________) 3) int find(int[] num){ int answer = 0; for(int k = 0; k < num.length; k++ ) for(int j = k; j< num.length; j++){ int current = 0; for(int i = k; i<=j; i++) current += num[i];
  • 3. if (current > answer) answer = current; } return answer; } Note: Given two indices i<=j of an array of integers num, the sum num[i]+ num[i+1] + …+ num[j] is called a sub-sum Comments What does the method do: Input size n = Worst case T(n) = O(________) Best case T(n) = O(________) 4) void printMany(int[]arr){ int N = arr.length; for(int k = 0 ; k< N; k++){ int p = k; while(p>0){ System.out.println(arr[p]+" "); p = p/2; } } Comments What does the method do: Input size n = Worst case T(n) = O(________) Best case T(n) = O(________) Solution 1) int find( int[] list, int element ){ int answer = 0; for(int k = 0; k < list.length; k++ ) //traversing array start to end if (element==list[k]) //checking for element answer++; // if element found, increase by 1 return answer; }//end method
  • 4. In the function given above, we can see an array ‘list’, and an integer ‘element’ being accepted as parameters. We initialize an integer ‘answer’, with an initial value of 0. What we are doing with this function is searching for the frequency of an element, in the list. The for loop starts at index 0, and goes on till the end of the array. At each iteration, the if statement checks whether the ‘element’ input by the user, is present in the list at the ‘kth’ position. Every time the element matches with the element present in the list, the value of ‘answer is incremented by 1. When the loop terminates, after having traversed the entire array, the variable ‘answer’ has a value stored, which is equal to the number of times the element input by the user, was found in the list. Hence, we get the frequency of the occurrence of an element in a list through this function. Note: This is a classic example of ‘Linear search’ for an element, where we search the entire list for an element. It has a complexity T(n)= O(n) for Both Worst Case, and Best Case. 2) code not clear. 3) 3) int find(int[] num){ int answer = 0; for(int k = 0; k < num.length; k++ ) //will traverse entire list for(int j = k; j< num.length; j++){ int current = 0; for(int i = k; i<=j; i++) // will traverse from k to j every time current += num[i]; if (current > answer) answer = current; // computing largest sub sum of list } return answer; //returning largest sub sum of list } On inspection, we can see that for k=0, and j=0, the i loop runs one time, and for k=0,j=1, the i loop runs twice, and so on. Therefore, we can say that the inner most loop is bound between the ‘k’ loop and the ‘j’ loop, ‘k’ being the lower bound, and ‘j’ being the upper bound. The inner most loop, bound between the values of k and j, calculates the sum of the elements ranging from k to j (the sub-sum). If this sum is found to be greater than the previously computed sub sum, then the answer is updated. The ultimate motive of this method is to find the largest sub sum of the given list.
  • 5. Let num.length() be n, Then the outmost loop runs n times. The second loop runs a total of n times when k=0, n-1 times when k=1, n-2 times for k=3 and so on, running for a total of n(n+1)/2 times (sum of numbers of 1-n; The third loop runs 1 time for k=0,j=0, 2 times for k=0,j=1 and so on. Therefore the complexity of this method is given by O(n^3). T(n)=O(n^3) (both worst and best cases). 4) void printMany(int[]arr){ int N = arr.length; for(int k = 0 ; k< N; k++){ int p = k; while(p>0){ System.out.println(arr[p]+" "); p = p/2; } } In this function, the outer k loop runs from 0 to N i.e. the entire list. For k=0, p-0, and hence the inner while loop does not run. For k=1, p=1, and hence the inner while loop runs 1 time, and prints 1 element. For k=2, p=2 and hence the inner while loop runs twice, and prints two elements. For k=3, p=3 and hence the inner while loop runs twice, and prints two elements. For k=4, p=4 and hence the inner while loop runs thrice, and prints three elements. For k=5, p=5 and hence the inner while loop runs thrice, and prints three elements. And so on, On further inspection, we find that the inner while loop runs and prints twice the number of elements, it has printed for a certain number of iterations of the outer loop i.e. the inner loop first runs 0 times, then it runs one time, then it runs two times, then it runs four times, and so on, or in other words the number of elements printed is growing in multiples of two. Analysis: The outer loop runs N times. The inner loop runs 1+2+4… times, i.e. in a geometric progression with common ratio of 2. The formula for sum of a GP is S=a({r^n}-1)/(r-1) Where r is the common ratio, a the first term. The complexity can then be represented as
  • 6. T(N)= O(n2^n) (both worst and best case).