Algorithm introduction 7.4-5

Source: Internet
Author: User

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 )).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.