207 views
1 vote
3. Recursive Algorithm Tracing. If the Sort algorithm (given below) is applied to the input list (3,4,1,2) how many exchanges are performed between elements in this input list? List each swap in the order in which it is made during the execution of the algorithm. Note that we are not talking about comparisons here, but rather only comparisons that result in an interchange. ( 5 points) Sort is the following sorting algorithm (which you may assume is correct), called initially with i=1 and j=n to sort a list of n numbers in array A : Sort(A,i,j)

1. if A[i]>A[j]
2. then exchange A[i]↔A[j]
3. if i+1≥j
4 then return 5 k←⌊(j−i+1)/3⌋
6 Sort(A,i,j−k)
7 Sort(A,i+k,j)
8 Sort(A,i,j−k)



User Greens
by
7.1k points

1 Answer

2 votes

To trace the number of exchanges and list each swap in the order they occur during the execution of the `Sort` algorithm on the input list (3, 4, 1, 2), let's step through the algorithm:

1. Initial input: (3, 4, 1, 2)

Now, let's follow the algorithm:

- i = 1, j = 4

- A[i] = 3, A[j] = 2 (A[i] > A[j] is true, so exchange)

Exchanged: (2, 4, 1, 3)

- Recursive call 1: Sort(A, 1, 4 - 1) -> Sort(A, 1, 3)

- i = 1, j = 3

- A[i] = 2, A[j] = 1 (A[i] > A[j] is true, so exchange)

Exchanged: (1, 4, 2, 3)

- Recursive call 2: Sort(A, 1, 3 - 1) -> Sort(A, 1, 2)

- i = 1, j = 2

- A[i] = 1, A[j] = 4 (A[i] <= A[j], no exchange)

- Recursive call 3: Sort(A, 1 + 1, 3) -> Sort(A, 2, 3)

- i = 2, j = 3

- A[i] = 2, A[j] = 4 (A[i] <= A[j], no exchange)

- Recursive call 1: Sort(A, 1, 3 - 1) -> Sort(A, 1, 2)

- i = 1, j = 2

- A[i] = 1, A[j] = 2 (A[i] <= A[j], no exchange)

- Recursive call 2: Sort(A, 1 + 1, 3) -> Sort(A, 2, 3)

- i = 2, j = 3

- A[i] = 2, A[j] = 3 (A[i] <= A[j], no exchange)

- i+1 >= j, so we return.

So, the total number of exchanges made during the execution of the `Sort` algorithm on the input list (3, 4, 1, 2) is 2, and the swaps occurred in the order mentioned above.

User PriestVallon
by
8.2k points