Question:
When the input data is "almost ordered", insertion sorting is very fast. In practice, we can use this feature to increase the speed of fast sorting. When fast sorting is called for a child array whose length is less than K, it is returned without any sorting. After a layer-by-layer Quick Sort call is returned, insert and sort the entire array to complete the sorting process. Proof: This sortingAlgorithmThe expected time complexity is O (NK + NLG (N/K )).
Solution:
Quicksort uses the insert sort method when recursion to an array with only a few elements. The improved quick sorting method is available in
Expected time = the expected time of the original fast sorting + the expected time of the insertion sorting method.
Here we still need to use the analysis method of Chapter 7.4 (Introduction to algorithms. The expected number of comparisons must be calculated for the quick ranking.
Because the elements that are divided into the same small array K won't be compared in the quick row. So Xij only needs to calculate those I and j difference more than K-1 elements can be compared.
Define an element set zij = {zi, Zi + 1, ZJ}
Define a random indicator variable Xij = I {zi and ZJ are compared}
E [Xij] = Pr [Xij] = Pr {zi and ZJ are compared} = Pr {zi is the principal component of zij} + Pr {ZJ is the principal component of zij} = 2/ (J-I + 1) // because the two can be compared in the fast sorting, one of them must be the principal component
The expected number of comparisons in quick sorting. E [Xij] is
So the expected time for the fast sorting is O (NLG (N/K). Assume that the optimized fast sorting produces a small array size O (K), in eachThe size of O (k) is sorted by insert in decimal groups. The time complexity isO (K ^ 2 ),If there are a total of O (N/K) small arrays, the insertion sorting time is O (NK ),. The total time is O (NK + nlog (N/K )).