• :00Days
  • :00Hours
  • :00Mins
  • 00Seconds
A new era for learning is coming soonSign up for free
Log In Start studying!

Select your language

Suggested languages for you:
Answers without the blur. Sign up and see all textbooks for free! Illustration

Q1SE

Expert-verified
Discrete Mathematics and its Applications
Found in: Page 233
Discrete Mathematics and its Applications

Discrete Mathematics and its Applications

Book edition 7th
Author(s) Kenneth H. Rosen
Pages 808 pages
ISBN 9780073383095

Answers without the blur.

Just sign up for free and you're in.

Illustration

Short Answer

a) Describe an algorithm for locating the last occurrence of the largest number in a list of integers.

b) Estimate the number of comparisons used.

(a) procedure last largest (a1,a2,an":integerswith"n2)

max:=a1

position: =1

for i:=2 to n

if ai>max then

max:=a1

position: =1

return position

(b) n-1,O(n)

See the step by step solution

Step by Step Solution

(a)Step 1: Write algorithm

Let us call the algorithm "last largest" and the input of the algorithm is a list of

integers a1,a2,,an .

procedure last largest (a1,a2,an:integerswith n2)

The variable "max" will keep track of the largest number and then variable "position"

will keep track of the position of the largest number. We initially define the maximum

as the first element.

max:=a1

position: =1

Next we compare every (other) element in the list with the current largest number. If

the element is larger than (or equal, since we are interested in the last occurrence)

the current largest number, then we replace the maximum by this element.

for i:=2 to n

if aimax then

max:=ai

position: =i

Finally, we return the position of the last occurrence of the largest number.

return position

Step 2: Algorithm

Combining these steps, we then obtain the algorithm:

procedure last largest (a1,a2,an:integerswith n2)

role="math" localid="1668488545991" max:=a1position:=1 for i=2 to nif aimax thenmax:=a1position:=1

return position

(b) Step 3: Number of comparisons

The algorithm only makes a comparison when aimax is executed, which

occurs in every iteration of the for-loop. Since can take on values from 2 to n,

there are n-1 iterations of the for-loop and thus n-1 comparisons are made, while n-1 is O(n) .

Recommended explanations on Math Textbooks

94% of StudySmarter users get better grades.

Sign up for free
94% of StudySmarter users get better grades.