"a" and "b" are two arrays. They both have "n" elements. What does the following algorithm do? Try the following example if you need an example: a[0] = 2, a[1] = 1, a[2] = 3, b[0] = -2, b[1] = 42, b[2] = 22, n = 3.
i %26lt;- 0
while (i %26lt; n) do
j %26lt;- i+1
m %26lt;- a[i]
while (j %26lt; n) do
if (m %26gt; a[j]) then
m %26lt;- a[j]
end if
j %26lt;- j + 1
end while
b[i] %26lt;- m
i %26lt;- i + 1
end while
Answer:
a. array b is an exact copy of array a
b. array a and array b are not related
c. array a becomes sorted, array b is not changed
d. array b is the sorted version of array a
e. none of the other descriptions is true
Can anyone please tell me how to do this and help me find out the answer?
"a" and "b" are two arrays. They both have "n" elements. What does the following algorithm do?
Sometimes adding some indents will help figure out what's going on. In your algorithm, you have a lot of nested if and while statements, so space them out like this first to see how each is related to each other (I'm using periods because Yahoo won't show spaces):
i %26lt;- 0
while (i %26lt; n) do
...j %26lt;- i+1
...m %26lt;- a[i]
...while (j %26lt; n) do
......if (m %26gt; a[j]) then
.........m %26lt;- a[j]
......end if
......j %26lt;- j + 1
...end while
...b[i] %26lt;- m
...i %26lt;- i + 1
end while
Your i is a counter that starts with 0, and your j is a counter that starts with 1. j will always be more than i.
The "while (i %26lt; n) do" line limits this algorithm to 3 loops, since n is 3.
Directly after this statement, j is established as a counter, and m is defined to be the i-th element of your matrix. The next while statement then compares m (the i-th element in the matrix) to the element after this (using j to read the next element).
If m is larger, then the if statement makes m take on the smaller value. If m is smaller, nothing happens and j is indexed to the next value. Then the process repeats itself. If we get to the end of the matrix and m isn't replaced anymore, it becomes the i-th value in matrix B. After this, i is indexed to the next element in matrix A and the entire process is repeated once again, until all of matrix A has been checked.
The result then is that through m, matrix A is sorted least to greatest and is written into matrix B, which is answer (d).
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment