Which of the following functions correctly computes the index of the first minim
ID: 3580327 • Letter: W
Question
Which of the following functions correctly computes the index of the first minimum element in any array a1, a2, ..., an? (Assume n 1.)
function FirstMinIndex (a1, a2, ..., an : Integers)
j := 1
x := a1
for i := 2 to n
if ai < x then
j := i
x := ai
return x
function FirstMinIndex (a1, a2, ..., an : Integers)
j := 1
x := a1
for i := 1 to n
if ai < x then
j := i
x := ai
return j
function FirstMinIndex (a1, a2, ..., an : Integers)
j := 1
x := a1
for i := 2 to n
if ai x then
j := i
x := ai
return j
function FirstMinIndex (a1, a2, ..., an : Integers)
j := 0
x := 0
for i := 1 to n
if ai < x then
j := i
x := ai
return j
function FirstMinIndex (a1, a2, ..., an : Integers)
j := 1
x := a1
for i := 2 to n
if ai < x then
j := i
x := ai
return x
function FirstMinIndex (a1, a2, ..., an : Integers)
j := 1
x := a1
for i := 1 to n
if ai < x then
j := i
x := ai
return j
function FirstMinIndex (a1, a2, ..., an : Integers)
j := 1
x := a1
for i := 2 to n
if ai x then
j := i
x := ai
return j
function FirstMinIndex (a1, a2, ..., an : Integers)
j := 0
x := 0
for i := 1 to n
if ai < x then
j := i
x := ai
return j
Explanation / Answer
The first algorithm is return the minimum value x, but the requirement is to return the minimum index. So, it doesn't qualify.
The third algorithm will change the index, if there are multiple indexes with the least value, and therefore, will return the last min index, and not the first one.
The last algorithm is starting from index 0, whereas the elements are from a1 ... an.
So, the second algorithm works perfectly for your requirement, i.e., to find the first index of minimum element in the array.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.