Consider the following selection sort algorithm. Assume that the input A is a random…
- User
Consider the following selection sort algorithm. Assume that the input A is a random permutation of n distinct numbers. Calculate the expected number of times the line min ← j is executed, and represent it by Θ. Selection-Sort(A): for i ← 1 to n − 1 do min ← i for j ← i + 1 to n do if A[j] < A[min] min ← j ▷ How many times is it executed in expectation? endif endfor swap A[min] and A[i] endfor
- Assistant
Let X be the number of times the line min ← j is executed. For each iteration of the inner loop, the probability of executing min ← j is equal to the probability of A[j] being the new minimum. Since there are n - i + 1 values remaining in the loop, the probability is 1/(n - i + 1). Therefore, the expected number of times min ← j is executed for each inner loop iteration is Σ((1/(n - i + 1)), where the summation is taken from i = 1 to n - 1.
So, X = Σ(1/(n - i + 1)).
To solve this summation, consider the Harmonic number H(n) = Σ(1/i) for integers i from 1 to n. The expected number X can be rewritten as follows:
X = H(n) - H(0) + H(n - 1) - H(1) + ... + H(1) - H(0).
X = H(n) - (n - 1) * H(1).
Since H(n) = ln(n) + O(1) (Euler's Harmonic number theorem), and H(1) = 1, we can approximate X as follows:
X ≈ ln(n) - (n - 1) * 1.
X = Θ(nlogn).
So, the expected number of times the line min ← j is executed is Θ(nlogn).
- User
explain why the values remaining in the loop is n-i+1
- Assistant
In the Selection-Sort algorithm, the outer loop iterates from i = 1 to n - 1. The inner loop iterates from j = i + 1 to n. At each step of the outer loop, we have already found the minimum value among the first i - 1 elements and moved it to its correct position.
Now, we need to find the minimum value in the remaining part of the array (from index i to n). The size of this remaining part is n - i + 1. The "+1" is included because both the start (i) and end (n) positions are inclusive.
For example, suppose n = 10 and you are at i = 4. Then, the remaining part of the array is from index 4 to 10 (inclusive), which has the size of 10 - 4 + 1 = 7 elements. That's why the values remaining in the loop is n - i + 1.