Westonci.ca is the premier destination for reliable answers to your questions, brought to you by a community of experts. Experience the ease of finding accurate answers to your questions from a knowledgeable community of professionals. Get precise and detailed answers to your questions from a knowledgeable community of experts on our Q&A platform.

Suppose that a list contains integers that are in order of largest to smallest and an integer can appear repeatedly in this list.
1) Devise an algorithm that locates all occurrences of an integer x in the list.
2) Estimate the number of comparisons used.
You must show/explain your work.


Sagot :

Answer:

(a) The algorithm is as follows:

count = 0

for i = 1 to n:

  if x = xi:

       count++

print(count)

(b) n comparisons

Explanation:

Solving (a):

Assume the integer to locate is x and the elements of the list are: [tex]x_1, x_2, x_3, x_4..... x_n[/tex]

Such that: [tex]x_1 \ge x_2 \ge x_3 ...... \ge x_n[/tex]

The algorithm is as follows:

count = 0

for i = 1 to n:

  if x = xi:

       count++

print(count)

The above iterates through the count of the list (i.e. n) and makes comparison with each element of the list (i.e. element 1 to element n).

When a match is found, the count variable is incremented by 1 and printed at the end of the loop

Furthermore:

If there are 3 elements in the list, the algorithm makes 3 comparisons.

It makes 10 comparisons if there are 10 elements in the list.

So: it makes n elements if there are n elements in the list