Introduction to algorithms Chapter 1 Introduction to sorting and sequence statistics Algorithms

Source: Internet
Author: User
1. concept I sequence statistic is the smallest element in the set. When N is an odd number, the median is the number that appears at I = (n + 1)/2. When N is an even number, the median appears at I = n/2 and I = (n + 1)/2 respectively. In this article, we ignore the parity of n. The median indicates the number at I = (n + 1)/2. This document assumes that the numbers in the set are different. Ii. Code

# Include <iostream> using namespace STD; // The Int length_a program in the book; void print (int * A) {int I; for (I = 1; I <= length_a; I ++) cout <A [I] <''; cout <Endl ;} ************************ * ****************************/INT minimun (int *) {int min = A [1], I; // view each element in the Set in sequence for (I = 2; I <length_a; I ++) // The minimum element in the record comparison process, if (min> A [I]) min = A [I]; return min ;} /********** calculate the minimum and maximum values through the 3n/2 Comparison ****************** ***** * *****************************/Void minandmax (int *, int & min, Int & MAX) {int I; // if n is an odd number if (length_a % 2 = 1) {// set the maximum and minimum values to the first element min = A [1]; max = A [1]; I = 2 ;} // if n is an even number of else {// compare the first two elements to determine the initial value min = min (A [1], a [2]) of the maximum and minimum values; max = A [1] + A [2]-min; I = 3;} // process the remaining elements in pairs for (; I <= length_a; I = I + 2) {// compare a pair of input elements to int A = min (A [I], a [I + 1]); int B = A [I] + A [I + 1]-A; // compare the smaller one with the current minimum value if (a <min) min =; // compare the larger vertex with the current maximum value Compare if (B> MAX) max = B ;}} ******************* * ***************** // It has already appeared many times, int partition (int * a, int P, int R) {int x = A [R], I = p-1, J; For (j = P; j <R; j ++) {if (a [J] <= x) {I ++; swap (A [I], a [J]) ;}} swap (A [I + 1], a [R]); return I + 1;} int randomized_partition (int * a, int P, int R) {// randomly select a number in the array as the principal int I = rand () % (r-p + 1) + P; swap (A [R], a [I]); // divide return partition (A, P, R);} // I is enabled from 1 Int randomized_select (int * a, int P, int R, int I) {If (P = r) return a [p]; // take an element as the primary element and divide the array into two groups, a [p .. q-1] <A [Q] <A [q + 1 .. r], returns the position of the principal component in the entire array int q = randomized_partition (A, P, R); // The principal component is the Q element in the entire array, which is a [p .. r] The K element in the array int K = Q-p + 1; // A [p .. in R], the I-th element if (I = k) // returns a [Q]; else if (I <k) // The element <principal element, in a [p .. return randomized_select (A, P, Q-1, I); else // The element> principal element, then in a [q + 1 .. r] to continue searching for retu Rn randomized_select (A, q + 1, R, I-k );} ******************* * *****************************/INT select (int *, int P, int R, int I); // sort the insertion of each group from start to end, and return the value. // The insertion sorting is very simple, int insert (int * a, int start, int end, int K) {int I, j; for (I = 2; I <= end; I ++) {int T = A [I]; for (j = I; j> = start; j --) {If (j = Start) A [J] = T; else if (a [J-1]> T) A [J] = A [J-1]; else {A [J] = T; break ;}} retu Rn a [start + k-1];} // according to the algorithm in this paper, find the median int find (int * a, int P, int R) {int I, j = 0; int start, end, Len = r-p + 1; int * B = new int [Len/5 + 1]; // a group of five elements, length: start to end, insert and sort each group, and return the median for (I = 1; I <= Len; I ++) {if (I % 5 = 1) Start = I + p-1; if (I % 5 = 0 | I = Len) {J ++; end = I + p-1; // sort the inserts from start to end in each group, and return the median value. If it is the last group, the number of elements in the group may be less than 5int ret = insert (a, start, end, (end-Start)/2 + 1 ); // pick out the values of each group to form a new array B [J] = ret;} // Recursively call select () to find the median int ret = select (B, 1, J, (J + 1)/2) for this array ); // Delete [] B; // it is strange that this sentence should be okay, but how can this sentence be left empty when it reaches? Return ret;} // F-based division int partition2 (int * a, int P, int R, int f) {int I; // locate the position of F and make it exchange with a [R] for (I = P; I <r; I ++) {if (a [I] = f) {swap (A [I], a [R]); break ;}} return partition (A, P, R) ;}// search for Array a [p .. the largest I element in R]. I is counted from 1, not from P. Int select (int * a, int P, int R, int I) {// If the array contains only one element, if (P = r) return a [p]; // based on the algorithm in the text, find the median int F = find (A, P, R); // use this median as the primary element, and return the median value in the entire array a [1 .. len] position // because the principal component is an element in the array, the Division is like this. A [p .. q-1] <= F <A [q + 1 .. r] int q = partition2 (A, P, R, f); // convert the value to the value in array a [p .. r] In the position int K = Q-p + 1; // compare with the searched element if (I = k) return a [Q]; else if (I <k) return select (A, P, Q-1, I); else // if the principal element is an element in the array, the latter half should write return select (, q + 1, R, I-k); // if the principal element is not an element in the array, change the latter half to select (A, Q, R, i-k + 1)} int main () {CIN> length_a; int * A = new int [length_a + 1], I, CNT; // generate test data for (I = 1; I <= length_a; I ++) A [I] = rand () % 100; CIN> CNT; // Display Test Data print (a); // output result if (CNT <= length_a) cout <select (A, 1, length_a, CNT) <Endl; return 0 ;}

 

Iii. Exercise 9.1 min and Max 9.1-1 see Introduction to Algorithms
9.1-1 calculate the second small element 9.2 and make the selection based on the expected Linear Time
9.2-3RANDOMIZED-SELECT(A, p, r, i) 1    while true 2        if p = r 3            then return A[p] 4        q <- RANDIMIZED-PARTITION(A, p, r) 5        k <- q - p + 1 6        if i = k 7            then return A[q] 8        else if i < k 9            then q <- q-110        else11            q <- q + 112            i <- i - k9.2-4    A = {3, 2, 9, 0, 7, 5, 4, 8, 6, 1}==> A = {3, 2, 0, 7, 5, 4, 8, 6, 1, 9}==> A = {3, 2, 0, 7, 5, 4, 6, 1, 8, 9}==> A = {3, 2, 0, 5, 4, 6, 1, 7, 8, 9}==> A = {3, 2, 0, 5, 4, 1, 6, 7, 8, 9}==> A = {3, 2, 0, 4, 1, 5, 6, 7, 8, 9}==> A = {3, 2, 0, 1, 4, 5, 6, 7, 8, 9}==> A = {2, 0, 1, 3, 4, 5, 6, 7, 8, 9}==> A = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}==> A = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}==> A = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
9.3 worst case Linear Time Selection

9.3-3

Select the value in the SELECT statement first, and then use the value to divide the data. For the code, see Introduction to algorithms-9.3-3.

Quicksort (A, P, R) 1 If P> R2 then return3 I <-(r-p + 1)/24 x <-select (A, P, R, I) 5 q <-partition (A, P, R, x) // division of X-based elements 6 quicksort (A, P, q-1) 7 quicksort (A, q + 1, r)

9.3-5

Select (A, P, R, I) 1 if p = R2 then return a [p] 3 x <-median (A, P, R) 4 q <-partition (A, P, R, X) // X-based division of 5 k <-Q-P + 16 if I = K7 then return a [Q] 8 else if I <K9 then return select (, p, Q-1, I) 10 else return select (A, q + 1, R, I-K)

9.3-6

Set the number of elements in each child set to T = N/K. A [J] is the element marked as J in array a, and a (j) is the element whose array is larger than J.

Then, the K quantile is a (t), A (2 T), A (3 T ),......, A (k-1) T)

Run Time (k-1) * N for the number of K-1 in order

To set the running time to O (nlgk), the improvement is not to look for the number of the K-1 in turn, but to use the method of binary to find.

First, find the k/2 quantile, and then use this quantile as the main element to divide the array into two sections, respectively for the two sections to find the quantile. At this time, the search range becomes smaller, and the efficiency is improved.

See introduction to algorithms-9.3-6

9.3-7

Step 1: obtain the value O (n) of the median of the array)

Step 2: Calculate the absolute value of the difference between each number and the median in the array and store it in another array B. O (N)

Step 3: Find the number ret o (n) in the k-th small of array B)

Step 4: Calculate the absolute value of the difference between array S and RET smaller than the number of RET and output O (N)

In step 4, we can also use the division method to find the absolute value of the difference between the array S and RET smaller than the number of ret.

For the code, see Introduction to algorithms-9.3-7.

9.3-8

Solve the problem recursively. The solution scale is halved. When there are four elements left, the solution is obtained.

Compare the values of Mina and minb in the two arrays.

If Mina = minb, this value is the result.

Otherwise, remove the first half of the array where the small one is located, and remove the latter half of the big one. (For the values of the two arrays, there are n-1 elements, and n elements are larger than them. But for Min (Mina, minb), at most only The N-2 element is smaller than it, so it must not be the result of the request, similarly remove the big half)

Then, calculate the values of the remaining two arrays in the same way until the two arrays contain four elements.

For the code, see Introduction to algorithms-9.3-8.

9.3-9

This question is actually quite simple, that is, it may not be able to find this rule.

To simplify this question, we do not consider the Y coordinate of the point. Assume that all the points are on a line perpendicular to the pipe.

If there are two verbs of AB in the upper and lower of the pipe l, no matter where the pipe is located (as long as it is between AB ), d [Al] + d [BL] = d [AB].

According to the above rules, each two points are divided into one group. The point in Group I is (the point in the Group I is large, the point in the I is small ), as long as the pipeline is between two points in each group, the total length can be minimized.

From the above reasoning, the answer is:

So that the value of X is S (I ),

If the number of vertices is odd, the pipe goes through the S (I) Point

If the number of points is an even number, the pipe is located between the S (I) and S (I + 1) (including the two points)

 

Iv. Questions 9-1 Maximum number of sorted I
A) Merge Sorting and heap sorting, O (nlgn) B) Heap sorting, O (N + ilgn) c) Fast sorting, O (N + ilgi)
9-2 Weighted Median

B)

Sort each element using a sorting algorithm with the worst case time of O (nlgn)

Accumulate the weights of elements until the formula in the question is met.

C)

Step 1: Find the principal component by using the algorithm of finding the median in select.

Step 2: divide the array into three parts by using the principal component, that is, a [1 .. q-1] <A [Q] <A [q + 1 .. R]

Step 3: Calculate the Weight Sum of a [1 .. q-1] <0.5 and a [1 .. q]> = 0.5, whether the formula in the question is satisfied

Step 4: If yes, a [Q] is the desired number.

Step 5: If this parameter is not met, continue to use this algorithm for recursive search. If it is too large, you can find the first half. If it is too small, you can find the second half.

For the code, see Introduction to algorithms-9-2-c-weighted median.

Post office location problem:

D) Conclusion

 

9-3 Small sequence statistics

A) To be resolved

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.