Introduction to Algorithms chapter Seventh-Quick sorting

Source: Internet
Author: User

7.1-1 refer to the method in figure 7-1 to illustrate the partition operation on the array a=<13,19,9,5,12,8,7,4,21,2,6,11>.
A: Golang implementation:

// Partition 分解重排步骤func Partition(a QuickSortInterface, p int, r int) int {    x := a.Get(r)    i := p - 1    for j := p; j < r; j++ {        if a.Get(j) < x {            i++            a.Swap(i, j)        }    }    a.Swap(i+1, r)    return i + 1}

The result is:

[9 5 8 7 4 2 6 11 21 13 19 12]

7.1-2 when array a[p: R] All the elements in the same value, what is the Q value returned by partition? Modify the partition so that when the array a[p: R] All elements in the same value, q=[(P+R)/2]
Answer: The value returned by partition is R; Change the fourth line to

if a.Get(j) < x  && j%2 == p%2

7.1-3 please briefly demonstrate that the time complexity of partition is O (n) on a subarray of size n
A: In the For loop, for each element of the subarray, a judgment is made that the cost of the operation time outside the loop is constant, so the complexity is O (n).

How does 7.1-4 modify the quicksort so that it can be sorted in non-incrementing order?
Answer: will be a. Get (j) < x condition changed to a. Get (j) > x.

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.