Article 10-Introduction to algorithms Chapter 7 exercise Solutions

Source: Internet
Author: User

7-1-1:

The blue circle indicates the principal component in the next sorting, and the red box indicates the elements that do not need to be sorted this time:

7-1-2:

Returns R. Here it must be processing the equal sign. For the element of the principal component, one is placed on the left, the other is placed on the right, and the other is crosstab;

Partition (A, P, R) x = A [R] I = p-1 flag = true // for processing control that is equal to X, // if it is true, place it on the left, if it is false, place it on the right for J = P to R-1 // here the equal sign is processed separately if a [J] = x and flag = true I = I + 1 exchange a [I] and a [J] flag =! Flag if a [J] <x I = I + 1 exchange a [I] And a [J] exchange a [I + 1] and a [R] return I + 1

7-1-3:

A total of (r-p + 1) cycles are performed, and all other operations are theta (1). Therefore, the total cost is Theta (N), where N = r-p + 1;

7-1-4:

Change the condition of partition to a [J]> = x;

7-3-1:

In the case of randomization, the probability of occurrence of the worst case is extremely low;

7-3-2:

It is to see how many times the random-partition program is called.

The final form of the program running result is divided into k segments, where each Division requires calling of the division program, so the number of calls to the division program is less than N,

For each sub-array divided into N-1 and 0, a total of N-1 sub-arrays are divided, that is, theta (N)

For each sub-array divided into two equal-size sub-arrays, the number of sub-arrays is also theta (N)

7-4 -*:

I am not familiar with probability analysis. I will try again later when I read introduction to algorithms;

For 7-4-5:

This problem goes back to the first discussion about merging and sorting. For arrays smaller than K, the performance of simple methods is better than recursive sorting;

Time Complexity:

The first step is to analyze the insertion sorting time:

Equivalent to sorting arrays of N/K segments in K size, the time complexity is NK, which has been proved in Chapter 2;

For quick sorting analysis, refer to the quick sorting analysis in the book. The height of the random version recursive tree is about: n/2 ^ h = k h = theta (lg (N/k), the cost of each layer is Theta (n ),. therefore, the complexity of fast sorting is Theta (NLG (N/k), and the total complexity is Theta (NK + NLG (N/K ))

For more information about the code, see quick sort.

7-1: (The Hoare division is correct)

Proof:


B. I, j makes it impossible to access elements other than a [P. R.

I increased from P-1, and J decreased from the second to the second;

1) if a [p + 1 .. the elements in R] are smaller than a [p]. In this case, the first cycle is I = P; j = r; at this time, the two are exchanged, and then the second loop is performed until I = r, to meet a [I] = x, and at this time J = R-1; at this time the end of the loop; so no access to a [p... elements other than R]

2) if all the elements in a [p + 1. R] are greater than a [p], the first loop, I = P, j = P; the two are equal and jump out of the loop directly.

3) if a [p + 1 .. in R], there are both elements greater than a [p] and less than or equal to a [p]. If a [k] is set to the last element less than or equal to a [p, the first loop will exchange a [p] and

A [K], then I increases, and J decreases. I> = J may occur. If this is not the case between them, I will increase to K, A [k]> = x; j will be reduced to P. At this time, a [p] <= K; at this time, k> P is required. At this time, the program exits;

C. From the proof above, it is concluded that the maximum possible J is a R-1, and the minimum possible is P.

D. When the program exits, I = J + 1 or I = J;

When I = J + 1 exits, a [p .. the elements in I-1 must be less than X, a [J + 1 .. the elements in R] are greater than X, and I = J + 1 is brought into a [p .. all elements in J] are less than X, a [J + 1 .. the elements in R] are greater than X;

When I = J exits, a [I] = A [J] = x is required. In this case, a [p... all elements in J-1] are less than X, a [J + 1 .. the elements in R] are greater than X. Because a [J] = X, a [p .. all elements in J] are smaller than a [J + 1 .. elements in r;


E. the pseudo-code commit will not be written.

7-2 (fast sorting for the same element ):

A. For fast randomization sorting, the time complexity is Theta (N ^ 2 );

However, theta (nlgn) is a complex algorithm that has been improved since 7-2)

B. pseudo code:

Partition '(A, P, R) x = A [R] I = p-1 COUNT = 1 // used to count the number of elements equal to X for J = P to (R-count) if a [J] <xi = I + 1 exchange a [I] with a [J] elseif A [J] = x exchange a [J] with a [R-count] Count = count + 1 // exchange a [I + 1 .. I + Count] And a [R-count + 1 .. r], // Where a [R-count + 1 .. r] is equal to X, a [p .. i] are less than X for j = 1 to count exchange a [I + J] with a [R-J + 1] Return (I + 1, I + count)

C. pseudo code:

QUICKSORT'(A,p,r)  if(p<r)    (q,t)=RANDOM-PARTTITON'(A,p,r)    if p<q        QUICKSORT'(A,p,q-1)    if t<r       QUICKSORT'(A,t+1,r)

C ++ code:

Struct pair {int low; int high; pair (int A = 0, int B = 0): low (A), high (B ){}}; template <typename T> pair partition (T * a, int low, int high) {T partition = A [High]; // select the principal element int I = low-1; int COUNT = 1; // equal to the number of distinct elements, 1 t TMP at the beginning; // The auxiliary variable for exchanging two elements for (Int J = low; j <= high-count; ++ J) {if (a [J] <distinct) {I = I + 1; // exchange a [I] And a [J] TMP = A [I]; A [I] = A [J]; A [J] = TMP ;} else if (a [J] = Clerk) {A [J] = A [High-count]; A [High-count] = clerk; ++ count; -- J;} // At this time, a [low .. all elements in I] are smaller than values, a [High-count + 1... the elements in high] are equal to // values, a [I + 1 .. the elements in High-count] are greater than values // exchange a [I + 1 .. I + Count] And a [High-count + 1 .. element in high] // here is to convert a [High-count + 1 .. high] is assigned to a [I + 1 .. I + Count], then a [I + 1 .. I + Count] is assigned with orders for (Int J = 0; j <count; ++ J) {A [High-J] = A [I + 1 + J]; A [I + 1 + J] = signature;} return pair (I + 1, I + count);} template <typename T> void random_quicksort (T * a, int low, int high) {If (low 

7-3 questions about probability are not very familiar;

7-4:

A. the process of this algorithm is: first, the function calls the Division function and is divided into a [p... q-1] And a [q + 1 .. r] two sub-arrays, and then the function pair a [p .. q-1] sorting, for a [p... q-1] after sorting out the order, P = q + 1, then a [q + 1 .. r] divides it into two arrays, sorts its left array, and then processes its right array according to the above method until P = r

B. The larger the array on the left, the larger the stack depth. Therefore, when the array is in ascending order, the stack depth is Theta (n)

C. Use the Randomization method, or add sub-arrays with fewer array elements to the stack:

TAIL-RECURSIVE-QUICKSORT(A,p,r)   while p<r      q=PARTITION(A,p,r)      if q-p>r-q TAIL-RECURSIVE-QUICKSORT(A,p,q-1)         p=q+1      else  TAIL-RECURSIVE-QUICKSORT(A,q+1,r) r=q-1

7-5 (dividing by three numbers ):

This question is also a probability question. I can only make it up when I read introduction to algorithms...

However, the Code implementation is quite simple, and the idea is quite simple. The time complexity of the three numbers to take the median is linear time. The ninth chapter will focus on median, which will not be detailed here.

7-6 (Fuzzy sorting ):

If you have done all the exercises carefully, you will find that this question has the same idea as 7-2,

Put the specific explanation in the Code;

# Include <iostream> # include <cstdlib> # include <ctime> using namespace STD;/* this program is slightly improved on Exercise 7-2. The basic program has the same content and philosophy, the first is that the input data type * changes --- to the interval type; the second is that after the elements that are equal to the principal element are found, immediately change the principal component to the public part of two equal elements * However, this program is not completed. Why? First, I am not very comfortable with the use of template programming, so the program I write is not aesthetic. I could have written a good function, but it only depends on the differences in template parameters, it can support most of the exercises in this chapter. The second is * sorting equal elements by low values. This function is not implemented, but it still comes down to the issue of template programming, the * template parameter compbylow should be passed for sorting. * some poor versions will be released first. I will write a more beautiful program in the last few days. If you see this article, you can also write a program by yourself to share */struct mypair {int low; int high; mypair (int A = 0, int B = 0): low (), high (B) {}}; // defines the relationship between intervals. The value must be greater than, less than, or equal to; struct interval {friend STD: ostream & operator <(STD :: ostream & OS, const interval & Inter); int low; int high; interval (int A = 0, int B = 0): low (A), high (B) {} // If a's high is less than B's low, A is less than bbool operator <(const interval & RHs) const {return (high <RHS. low);} // if the low of A is greater than the high of B, A is greater than bbool operator> (const interval & RHs) const {return (low> RHS. high);} // the remainder is considered equal, that is, the two overlap bool operator = (const interval & RHs) const {return (low <RHS. high) & (high> RHS. low);} // In fact, this program is to take the intersection of two intervals and define it here. The previously written partition code void change (const interval & RHs) {high = min (high, RHS. high); low = max (low, RHS. low) ;}}; STD: ostream & operator <(STD: ostream & OS, const interval & Inter) {OS <"[" <Inter. low <"," <Inter. high <"]" <"; return OS ;}// set T to the template that defines the type of the change function <typename T> void change (T & LHS, const T & RHs) {LHS. change (RHs);} template <typename T> mypair partition (T * a, int low, int high) {T partition = A [High]; // select the main element int I = low-1; int COUNT = 1; // equal to the number of distinct elements, initially 1 t TMP; // auxiliary variable for (Int J = low; j <= high-count; ++ J) {if (a [J] <distinct) {I = I + 1; // exchange a [I] And a [J] TMP = A [I]; A [I] = A [J]; A [J] = TMP;} else if (a [J] = cursor) {change (cursor, a [J]); TMP = A [J]; A [J] = A [High-count]; A [High-count] = TMP; ++ count; -- J ;}// at this time, a [low .. all elements in I] are smaller than values, a [High-count + 1... the elements in high] are equal to // values, a [I + 1 .. the elements in High-count] are greater than values // exchange a [I + 1 .. I + Count] And a [High-count + 1 .. element in high] // here is to convert a [High-count + 1 .. high] is assigned to a [I + 1 .. I + Count], then a [I + 1 .. I + Count] is assigned as limit for (Int J = 0; j <count; ++ J) {TMP = A [High-J]; A [High-J] = A [I + 1 + J]; A [I + 1 + J] = TMP;} return mypair (I + 1, I + count);} template <typename T> mypair random_partition (T * a, int low, int high) {// random array R, make a [R] A principal int r = high; srand (unsigned) Time (null); // seed r = (RAND () % (high-low + 1) + low; // generate [low .. value Between High [// exchange a [R] And a [High] t tmp; TMP = A [R]; A [R] = A [High]; A [High] = TMP; return partition (A, low, high);} template <typename T> void random_quicksort (T * a, int low, int high) {If (low 

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.