Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

8. Consider the following program: Require: input array A with n > 0 items 1: m

ID: 3872017 • Letter: 8

Question

8. Consider the following program:

Require: input array A with n > 0 items

1: m = x = A[0]

2: for i=1; i < n 1; by i+=2 do

3: if A[i] < A[i + 1] then

4: if A[i] < m then

5: m = A[i]

6: end if

7: if A[i + 1] > x then

8: x = A[i + 1]

9: end if

10: else

11: if A[i + 1] < m then

12: m = A[i + 1]

13: end if

14: if A[i] > x then

15: x = A[i]

16: end if

17: end if

18: end for

19: if i == n 1 then

20: if A[i] < m then

21: m = A[i]

22: end if

23: if A[i] > x then

24: x = A[i]

25: end if

26: end if

(a) (2 points) What is the purpose (i.e., the input and output) of the program?

(b) (12 points) Prove the correctness of the algorithm using a loop invariant.

(c) (3 points) State a best-case runtime scenario.

(d) (3 points) State a worst-case runtime scenario.

(e) (8 points) Determine an equation T(n) for the worst-case runtime. To do so, you will need to let each simple operation (+, =, array access, if statement, <, etc.) have cost 1. For example, line 24 will have a total cost of 3 as a result of (+1) accessing an array (i.e., A) and (+1) an element of the array (i.e., A[i]) and then (+1) assigning the value to variable x.

(f) (10 points) Provide a tight bound on T(n). Be rigorous in your answer.

Explanation / Answer

a) The purpose of Program is to print the smallest and largest number after comparison.

It is comparing with all numbers.

b) Set m = x = A[0]

for i=1; i < n 1; by i+=2

Compare if A[i] < A[i + 1] then if A[i] < m then

Set m = A[i] Then Compare if A[i + 1] > x then

x = A[i + 1]

else

if A[i + 1] < m then m = A[i + 1]

if A[i] > x then x = A[i]

if i == n 1 then if A[i] < m then

m = A[i]

if A[i] > x then

x = A[i] End of the program

c) Best runtime is : Big(o) Notation where 0<A[i]>1 It lies in best condition and Result true.

A[i] < A[i + 1] then

if A[i] < m

m = A[i]

A[i + 1] > x then

x = A[i + 1]

d) Worst case scenerio is when omega(o) is tightly bound in it as it does not satisfy the condition.

omega(O)<1 which is tightly bound in it.

When result does not gives the true value then its the worst case.

e) Here we have put

if i == n 1 where i =2 and compare \ Cost 1

if A[i] < m then cost 3

m = A[i] \ Cost 1

end if \ Cost 1 as its sending the equstion to next statement

if A[i] > x then \ Cost 3

x = A[i] \cost 3

end if \Cpst 1

After getting all the cost we get a scenerio where it is satisfying the cost and situation and comaprison is done.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote