(3 points) Consider the following algorithm. // Assume that n is a positive inte
ID: 3848321 • Letter: #
Question
(3 points) Consider the following algorithm.
// Assume that n is a positive integer (= i.e. n > 1), and A[1..n] is a global array.
// Note that the index of array A starts from one, not zero.
// And also, don’t forget the array A in the algorithm is global.
Algorithm DoSomething (n)
1. if (n = 1)
2. print the current content of the whole array A on the screen;
3. else
4. for i <- 1 to n do
5. DoSomething(n – 1); // Recursive call.
6. if n is odd
7. swap A[1] and A[n];
8. else
9. swap A[i] and A[n];
10. return;
(a) Present execution result of the algorithm where an array A has “5”and n is 1.
(b) Present execution result of the algorithm where an array A has “5, 7”and n is 2.
Explanation / Answer
a.) for n=1, given algo. will print the array as it is i.e., Output = 5.
b.) for n=2, loop will iterate 2 times.
For i=1, it will call DoSomething(1) which will output the contents of array A i.e., Output: 5 7. Since, n is even, swap a[1] with a[2]. Now, a has values [7,5].
for i=2, it will call DoSomething(1) which will output the contents of array A i.e., Output: 7 5. Since, n is even, swap a[2] with a[2]. Now, a has values [7,5]. So, final output will be:
5 7
7 5.
Hope it helps, feel free to comment in case of any query.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.