The kettle problem requires us to pair the red and blue water bottle. How to make the red and blue water bottle one by one corresponding, that is to sort them separately. So this is sorted by the idea of a fast line, the Red Kettle array is sorted using the pivot in the blue water bottle, and the blue kettle is sorted using pivot in the red water bottle. Due to the condition of the Red Kettle has a corresponding blue water bottle, and vice versa, and the red kettle inside are different, so the order is very simple, a little modification of the quick row can get results.
A. Walk through all the red kettles, and compare each red water bottle with all the blue kettles, with a comparison of θ (N2).
B. Use a decision tree model, but here each branch has three, corresponding to less than and equal. Since each pair has at least one leaf node corresponding, the number of comparisons is lower than Ω (NLGN). The number of matches here can be seen as how many ways to put n different balls into n different buckets (only one ball per bucket).
C. The random algorithm is similar to the random version of the partition, the difference is two times each time, so the expected run time is unchanged. The worst case is O (N2).
#include <iostream>#include <algorithm>UsingNamespaceStdint Jug_partition (int *a,int P,int R,IntKey);void Jug_sort (int *r,int *b,int P,IntR) {if (P >=RReturn;int pivot = p + rand ()% (R-p +1); Swap (R[pivot], r[r]);int q=Jug_partition (B, p, R, R[r]); Jug_partition (R, p, R, B[q]); Jug_sort (R, B, p, Q-1); Jug_sort (R, B, q +1, r);}int Jug_partition (int *a,int P,int R,IntKey) {int i = P-1;Int J =Pfor (; J <= R; + +)j) {if (A[J) <Key) {+ +I Swap (A[j], a[i]); } }for (j = i +1; J <= R; ++Jif (a[j] = =Key) {+ +I Swap (A[j], a[i]);Break; }Returni;}IntMain () {int r[10] = {1,2,3,4,5,99,7,8,9,10};int b[10] = {10,9,8,7, 99, 5, 4, 3, 2, 1 }; Jug_sort (R, B, 0, 9for " cout << Endl; for auto r:r cout << r << ""
Introduction to the algorithm of Kettle problem 8.4