Finding number C of key comparisons and number M of moves - algorithm

I'm reading N.Wirth - Algorithms and Data Structures now. (Oberon version: August 2004)
The Question: how did he count these C and M? There is no explanation of this process... (any help will be useful)
Let me tell you what is the matter... I came across the following:
2.2.1 Sorting by Straight Insertion
... A good measure of efficiency is obtained by counting the numbers C of
needed key comparisons and M of moves (transpositions) of items.
He describes how does this algorithm work:
PROCEDURE StraightInsertion;
VAR i, j: INTEGER; x: Item;
BEGIN
FOR i := 1 TO n-1 DO
x := a[i]; j := i;
WHILE (j > 0) & (x < a[j-1] DO a[j] := a[j-1]; DEC(j) END ;
a[j] := x
END
END StraightInsertion
...and then he tells about C and M. But he doesn't explain the process of finding them --> he just shown the counted Cmin, Mmax... :
Analysis of straight insertion. The number Ci of key comparisons in the i-th sift is at most i-1, at least 1, and --- assuming that all permutations of the n keys are equally probable --- i/2 in the average. The number Mi of moves (assignments of items) is Ci + 2 (including the sentinel). Therefore, the total numbers of comparisons and moves are:
Cmin = n-1 Mmin = 3*(n-1)
Cave = (n^2 + n - 2)/4 Mave = (n^2 + 9n - 10)/4
Cmax = (n^2 + n - 4)/4 Mmax = (n^2 + 3n - 4)/2
So the question is:
how did he count these C and M? He doesn't explain the process of finding all of these numbers. Can you help me to understand how to find them? Any help will be good.
PS
I have been looking for the information on this subject, but with no result.
Additionally:
Here is the process of insertion shown in an example of eight numbers chosen at random (if needed):
Initial Keys: 44 55 12 42 94 18 06 67
v
i=1 44 55 12 42 94 18 06 67
v
v-----<
i=2 12 44 55 42 94 18 06 67
v
v-----<
i=3 12 42 44 55 94 18 06 67
v
i=4 12 42 44 55 94 18 06 67
v
v-----------<
i=5 12 18 42 44 55 94 06 67
v
v-----------------<
i=6 06 12 18 42 44 55 94 67
v
v--<
i=7 06 12 18 42 44 55 67 94

C is the number of comparisons and M is the number of data items moved. If we go by your example, on iteration 1, there is 1 comparison and no move. On iteration 2, there are 2 comparisons and 2 moves. And so on. Now, let us consider kth iteration. There will be k comparisons and assuming that your exact spot is halfway from 1 to k, there will be k/2 moves.
The number C and M are the sum of all comparisons and movements when k changes from 1 to n. All you have to do is to add up the summations, varying k from 1 to n and you have the numbers.

Related

Quickly compute `dot(a(n:end), b(1:end-n))`

Suppose we have two, one dimensional arrays of values a and b which both have length N. I want to create a new array c such that c(n)=dot(a(n:N), b(1:N-n+1)) I can of course do this using a simple loop:
for n=1:N
c(n)=dot(a(n:N), b(1:N-n+1));
end
but given that this is such a simple operation which resembles a convolution I was wondering if there isn't a more efficient method to do this (using Matlab).
A solution using 1D convolution conv:
out = conv(a, flip(b));
c = out(ceil(numel(out)/2):end);
In conv the first vector is multiplied by the reversed version of the second vector so we need to compute the convolution of a and the flipped b and trim the unnecessary part.
This is an interesting problem!
I am going to assume that a and b are column vectors of the same length. Let us consider a simple example:
a = [9;10;2;10;7];
b = [1;3;6;10;10];
% yields:
c = [221;146;74;31;7];
Now let's see what happens when we compute the convolution of these vectors:
>> conv(a,b)
ans =
9
37
86
166
239
201
162
170
70
>> conv2(a, b.')
ans =
9 27 54 90 90
10 30 60 100 100
2 6 12 20 20
10 30 60 100 100
7 21 42 70 70
We notice that c is the sum of elements along the lower diagonals of the result of conv2. To show it clearer we'll transpose to get the diagonals in the same order as values in c:
>> triu(conv2(a.', b))
ans =
9 10 2 10 7
0 30 6 30 21
0 0 12 60 42
0 0 0 100 70
0 0 0 0 70
So now it becomes a question of summing the diagonals of a matrix, which is a more common problem with existing solution, for example this one by Andrei Bobrov:
C = conv2(a.', b);
p = sum( spdiags(C, 0:size(C,2)-1) ).'; % This gives the same result as the loop.

QuickSort with middle elemenet as pivot

I am trying to search for any explanation on how Quick sort works with middle element as pivot but I couldn't find any. What I am trying to look for is there any demo on how the numbers are sorted step by step because its really hard understanding the algorithms. Thanks.
The vertical bars are around the pivot:
61 11 93 74 75 21 12|55|81 19 14 86 19 79 23 44
44 11 23|19|14 21 12 19
19|11|12 14
11
19|12|14
12
|19|14
14
19
19|21|23 44
|19|21
19
21
|23|44
23
44
81 55 75|86|74 79 93 61
81 55|75|61 74 79
74|55|61
55
|74|61
61
74
75|81|79
|75|79
75
79
81
|93|86
86
93
11 12 14 19 19 21 23 44 55 61 74 75 79 81 86 93
Based on this variation of Hoare partition scheme:
void QuickSort(int a[], int lo, int hi) {
int i, j, p;
if (lo >= hi)
return;
i = lo - 1;
j = hi + 1;
p = a[(lo + hi)/2];
while (1)
{
while (a[++i] < p) ;
while (a[--j] > p) ;
if (i >= j)
break;
swap(a+i, a+j);
}
QuickSort(a, lo, j);
QuickSort(a, j + 1, hi);
}
Note that the pivot can end up in either the left or right part after partition step.
Quicksort chooses a pivot value and moves the smaller elements to the beginning of the array and the larger elements to end. This is done by repeatedly scanning from both ends until a pair large/small is found, and swapped.
After such a partition process, all elements smaller than the pivot are stored before those larger than the pivot. Then the process is repeated on both subarrays, recursively. Of course when a subarray reduces to one or two elements, sorting them is trivial.
Recall that the pivot value can be chosen arbitrarily, provided there exist at least one element smaller and one larger in the array.

Time complexity for a very complicated recursion code

I have some problem while trying to calculate time complexity for this code:
function foo (int a):
if a < 1:
return 1
else:
for i = 1 to 4:
foo(a - 3)
for i = 1 to 4:
foo(a / 2)
end function
As far as I can go:
T(n) = 1 if n<1
T(n) = 4T(n-3) + 4T(n/2) if n>=1
= 4(4T(n-6) + 4T((n-3)/2)) + 4(4T(n/2 - 3) + 4T(n/4))
~ 4^2 (T(n-6) + T((n-3)/2) + T(n/2-3) + T(n/4))
Now, it is very complicated, since number of the next T increase by 2^n and also the child is quite complicated.
Is there any other ways to solve this problem?
Let's expand the recursive cost function:
T(n) = 4 [T(n-3) + T(n/2)]
T(n) = 4^2 [T(n-6) + T((n-3)/2) + T((n-6)/2) + T(n/4)]
T(n) = 4^n [T(n-9) + 2*T((n-6)/2) + T((n-9)/2) + T((n-12)/4) + T((n-3)/4) + T((n-6)/4) + T(n/8)]
From the moment the x in T(x) drops below 1, you should replace T(x) with 1. And from that moment on, the T(x) doesn't generate any "children" anymore so to speak.
what does this means? It means that after the k-'th expansion of T(n), the function will look like:
T(n) = 4^k [number of paths with length `k`]
and keep increasing k until all paths have "died". This is definitely the case after n/3 iterations, because that's the longest possible path.
We thus have some kind of graph, for instance for n=9:
9 + 6 + 3 + 0
| | ` 1
| `3 + 0
| ` 1
`4 + 1
` 2 + -1
` 1
so 6 paths. Now the problem is how to count the number of paths. In order to do this we will first represent the main path: n, n-3, n-6, etc. as a horizontal line of nodes, this is definitely the longest path:
n n-3 n-6 n-9 ... 1
Now out of all these nodes, do originate nodes of i -> i/2 (except for one)
n n-3 n-6 n-9 ... 4 1
| | | |
n/2 (n-3)/2 (n-6)/2 (n-9)/2 ... 2
(the second row shows all nodes created by divisions by 2). Now these nodes, generate again offsprong n -> n-3, which is, since it is divided by two n/2 -> (n-6)/2, in other words, there are edges that make jumps of two:
n n-3 n-6 n-9 ... 4 1
| | /-----+-------(n-9)/2 |
n/2 (n-3)/2 (n-6)/2 (n-9)/2 ... 2
\---------->(n-6)/2 \------->...
on other words, except for the first two elements, all other nodes in the second row count for two. If we would represent it as some kind of graph with the nodes labeled by their weight, it would look like:
1 -- 1 -- 1 -- 1 -- 1 -- .. -- .. -- 1
| | | | | | |
1 -- 1 -- 2 -- 2 -- 2 -- .. -- 2
Or if we keep doing this for this process:
1 -- 1 -- 1 -- 1 -- 1 -- .. -- .. -- .. -- .. -- ..-- 1
| | | | | | | | | |
1 -- 1 -- 2 -- 2 -- 2 -- .. -- .. -- .. -- .. -- 2
| | | | | | | |
1 -- 1 -- 2 -- 2 -- 3 -- .. -- .. -- 4
(the third row generates children 4 items further)
Now we need to calculate the sum of the last row. This is at most O(log n).
Which thus results in an upper bound of O(4^(n/3)*log n) maximum. It is definitely possible that the bound is tighter, or 4^(n/3+epsilon), the log doesn't really matter when it comes down to the exponent.
Experiments
One can turn the program into a program that calculates the cost (used Python):
def memodict(f):
""" Memoization decorator for a function taking a single argument """
class memodict(dict):
def __missing__(self, key):
ret = self[key] = f(key)
return ret
return memodict().__getitem__
#memodict
def foo (a):
if a < 1:
return 1
else:
return 1+4*(foo(a-3)+foo(a//2))
for i in range(1000) :
print '{0} {1}'.format(i,foo(i))
mind the 1+ (this is due to the fact that calling a method not at the leaves requires computational cost as well).
It shows the following graph (with the y axis in log space):
If one looks very closely it looks as if log n is a better estimate. Although I don't know if it is safe to say this.
This results in a table (below, calculated it further up to 2'000).
1 9
2 41
3 41
4 201
5 329
6 329
7 969
8 2121
9 2121
10 5193
11 9801
12 9801
13 22089
14 43081
15 43081
16 96841
17 180809
18 180809
19 395849
20 744009
21 744009
22 1622601
23 3015241
24 3015241
25 6529609
26 12149321
27 12149321
28 26290761
29 48769609
30 48769609
31 105335369
32 195465801
33 195465801
34 422064713
35 782586441
36 782586441
37 1688982089
38 3131929161
39 3131929161
40 6758904393
41 12530692681
42 12530692681
43 27038593609
44 50129261129
45 50129261129
46 108166435401
47 200529105481
48 200529105481
49 432677802569
50 802142540361
51 802142540361
52 1730759807561
53 3208618758729
54 3208618758729
55 6923087827529
56 12834580197961
57 12834580197961
58 27692546388553
59 51338515870281
60 51338515870281
61 110770380632649
62 205354484822601
63 205354484822601
64 443082304393801
65 821418721153609
66 821418721153609
67 1772329999438409
68 3285676572873289
69 3285676572873289
70 7089323128099401
71 13142709421838921
72 13142709421838921
73 28357295642743369
74 52570844443284041
75 52570844443284041
76 113429195098690121
77 210283390300852809
78 210283390300852809
79 453716792922477129
80 841133588239028809
81 841133588239028809
82 1814867221812679241
83 3364534403078885961
84 3364534403078885961
85 7259468937373487689
86 13458137720469918281
87 13458137720469918281
88 29037875950010995273
89 53832551082396717641
90 53832551082396717641
91 116151504000561025609
92 215330204762252612169
93 215330204762252612169
94 464606016804360524361
95 861320819851126870601
96 861320819851126870601
97 1858424068019558519369
98 3445283281135218692681
99 3445283281135218692681
100 7433696275286804238921
101 13781133127749444932169
102 13781133127749444932169
103 29734785104355787117129
104 55124532517920818958921
105 55124532517920818958921
106 118939140430257623503433
107 220498130084517750870601
108 220498130084517750870601
109 475756561733864969048649
110 881992520365763354792521
111 881992520365763354792521
112 1903026246986798196986441
113 3527970081514391739961929
114 3527970081514391739961929
115 7612104987998531108737609
116 14111880326168337145401929
117 14111880326168337145401929
118 30448419952199478498431561
119 56447521304878702645088841
120 56447521304878702645088841
121 121793679809003268057207369
122 225790085219957892102885961
123 225790085219957892102885961
124 487174719236834490168119881
125 903160340880652986350834249
126 903160340880652986350834249
127 1948698876948159378611769929
128 3612641363524384274620912201
129 3612641363524384274620912201
130 7794795507795923189331694153
131 14450565454100822773368263241
132 14450565454100822773368263241
133 31179182031186978432211391049
134 57802261816410380413470806601
135 57802261816410380413470806601
136 124716728124761056435137057353
137 231209047265654664360174719561
138 231209047265654664360174719561
139 498866912499057368446839722569
140 924836189062647014733211275849
141 924836189062647014733211275849
142 1995467649996282044625046245961
143 3699344756250640629770532459081
144 3699344756250640629770532459081
145 7981870599985180749337872339529
146 14797379025002675948264700809801
147 14797379025002675948264700809801
148 31927482399940933280729262494281
149 59189516100010914076436576375369
150 59189516100010914076436576375369
151 127709929599763943406294823113289
152 236758064400044110022526700261961
153 236758064400044110022526700261961
154 510839718399056614758740495864393
155 947032257600177281223668004459081
156 947032257600177281223668004459081
157 2043358873596227300168523186868809
158 3788129030400710939761843707744841
159 3788129030400710939761843707744841
160 8173435494384912565208445703590473
161 15152516121602847123581727787094601
162 15152516121602847123581727787094601
163 32693741977539653625368135770477129
164 60610064486411395753795798399095369
165 60610064486411395753795798399095369
166 130774967910158627959610155397452361
167 242440257945645596473320805911925321
168 242440257945645596473320805911925321
169 523099871640634525296578233905353289
170 969761031782582414931158973141652041
171 969761031782582414931158973141652041
172 2092399486562538155018863817501086281
173 3879044127130329713557186774446281289
174 3879044127130329713557186774446281289
175 8369597946250152673908006151884018249
176 15516176508521318970380250897829106249
177 15516176508521318970380250897829106249
178 33478391785000610910962228937122943561
179 62064706034085276096851207920903295561
180 62064706034085276096851207920903295561
181 133913567140002443859179120078078644809
182 248258824136341104852010847685857284681
183 248258824136341104852010847685857284681
184 535654268560009776298037299361325027913
185 993035296545364420269364209792439587401
186 993035296545364420269364209792439587401
187 2142617074240039106053470016494310560329
188 3972141186181457682935880906387200447049
189 3972141186181457682935880906387200447049
190 8570468296960156427659163345381749723721
191 15888564744725830735188806904953309270601
192 15888564744725830735188806904953309270601
193 34281873187840625714081936660931506377289
194 63554258978903322948188923891891471159881
195 63554258978903322948188923891891471159881
196 137127492751362502870108879768266900279881
197 254217035915613291806536828692106759410249
198 254217035915613291806536828692106759410249
199 548509971005450011494216652197608475890249
200 1016868143662453167255882099869574254596681
(Rewrote to give a better answer.)
Here is a simple and rigorous analysis that shows why T(n) ~ 4^{n/3} is a tight estimate.
We have the recurrence
T(n) = 4T(n-3) + 4T(n/2)
To get the tight result, we want to see that T(n/2) is negligible compared to T(n-3). We can do this as follows.
First, T is nonnegative for all n, so in particular T(n/2) >= 0, so for all n we have an inequality,
T(n) >= 4T(n-3)
Now, we want to use that inequality to compare T(n-3) and T(n/2).
By applying that inqeuality n/6 - 1 times, we get that
T(n-3) >= 4^{n/6 - 1} * T(n/2)
(Because, (n/6 - 1) * 3 = n/2 - 3, and n/2 - 3 + n/2 = n - 3).
It implies that T(n/2) is small compared to T(n-3):
T(n/2) <= 4^{-n/6 + 1} * T(n-3)
Now, for any epsilon > 0, there is an n_0 such that for n > n_0, 4^{-n/6 + 1} < epsilon. (Because, the limit of 4^{-n/6 + 1} is zero as n gets large.)
This implies that for any epsilon > 0, there is large enough n so that
4T(n-3) <= T(n) <= (4 + epsilon) T(n-3)
This yields the tight bound T(n) = 4^(n/3 + o(n)).
Getting a sharper estimate
There's some question in the comments about getting rid of the o(n) above, to get an even sharper estimate.
I fear this is basically just going to get pedantic -- usually no one cares about the low order terms, and nailing them down exactly is just some calculus work. But we can do a little more today anyways.
What's the difference
First of all, what is the difference between O(4^{n/3}) and 4^{n/3 + o(n)}? (Alternatively, we could write the latter as (4+o(1))^{n/3}.)
The difference is in how tightly they control the low order terms. O(4^{n/3}) controls them very tightly -- it says you don't exceed the (concrete) value 4^{n/3}) by more than a constant factor.
4^{n/3 + o(n)}, allows that you may exceed 4^{n/3} by more than a constant factor. But that factor is subexponential in n, it's negligible compared to 4^{n/3}.
For example, consider the function f(n) = n * 4^{n/3}. This function is not O(4^{n/3}). Indeed, it exceeds it by a factor n, more than a constant factor.
However, f(n) is in the class 4^{n/3 + o(n)}. Why? Because n = O(4^{epsilon n}) for every epsilon > 0.
When you have an inequality like,
4T(n-3) <= T(n) <= (4 + epsilon) T(n-3)
for every epsilon > 0, you can only deduce from this T(n) = (4 + o(1))^{n/3}.
To get a sharper bound, we need to treat epsilon as a function of n and not as a constant (like I did in the lazier version.)
Proof
Let epsilon(n) = 4^{-n/6 + 1} in what follows. Then we already showed
T(n) <= (4 + epsilon(n)) T(n-3)
and we want to see T = O(4^{n/3}).
This is can be expanded as an iterated product:
T(n) = PI_{i=1}^{n/3} (4 + epsilon(3i))
We can factor each term and pull out a factor of 4 to get
T(n) = 4^{n/3} * PI_{i=1}^{n/3} (1 + epsilon(3i)/4 )
The goal is now to show that
PI_{i=1}^{n/3} (1 + epsilon(3i)/4 ) = O(1)
and then we will be finished.
To do this we take the log, and show that that is O(1).
SUM_{i=1}^{n/3} log(1 + epsilon(3i/4))
We bound that using log(1+x) <= x for x >= 0.
SUM_{i=1}^{n/3} epsilon(3i/4)
Now we use the definition of epsilon. In fact we only need to know epsilon(n) <= C^{-n} for some C > 1. The above becomes
SUM_{i=1}^{n/3} C'^{-i}
for some constant C' > 1. But this is a geometric series, so it is bounded above by the infinite geometric series as
1 / (1 - 1/C') = O(1)
Thus T(n) = O(4^{n/3}).
Since we already had T(n) = Omega(4^{n/3}) we now have it tight up to constants, T(n) = Θ(4^{n/3})
You can decide for yourself if this extra work made things any more clear :p Personally I prefer to leave the o(n)'s in there usually.
IMO, the time complexity is Θ(r^n), where r=³√4.
Indeed, plugging this expression in the recurrence relation,
r^n = 1 + 4 r^n / r³ + 4 r^(n/2) = 1 + r^n + 4 √(r^n),
where the second term dominates asymptotically.
Here is a plot of the exact number of total calls to foo, divided by r^n for easy reading. We assumed the floor [n/2] in f(n/2).
The ratios tend to the repeating sequence 46.6922952502, 63.4656065932
74.1193985991. This seems to confirm Θ(r^n).
Update:
By induction we can show that for n >= 21,
T(n) < B(n) = 75.(s^(2n) - 4.s^n),
with s=³√2.
Indeed, by the recurrence equation and the induction hypothesis,
T(n+3) = 1 + 4.T(n) + 4.T([(n+3)/2])
< 1 + 4.75.(s^(2n) - 4.s^n) + 4.75.(s^(2[(n+3)/2])) - 4.s^[(n+3)/2])
We compare this to the bound B(n+3) to establish
1 + 4.75.(s^(2n) - 4.s^n) + 4.75.(s^(2[(n+3)/2])) - 4.s^[(n+3)/2])
< 75.(s^(2n+6) - 4.s^[(n+3)/2]
We can simplify the terms 4.75.s^(2n) and divide by 300.s^n:
s^(-n)/300 - 4 + s^(-(n+3)%2) - 4.s^([(n+3)/2]-n) < - s^([(n+3)/2]-n)
or
s^(-n)/300 + s^(-(n+3)%2) < 4 + 5.s^([(n+3)/2]-n).
This inequality is true for any n, so that T(n) < B(n) => T(n+3) < B(n+3).
Now for the base case, we use the table of T(n) given by #CommuSoft (and checked independently) and verify numerically
T(21) = 744009 < 75.(s^42 - 4.s^21) = 1190400
T(22) = 1622601 < 75.(s^44 - 4.s^22) = 1902217.444...
T(23) = 3015241 < 75.(s^46 - 4.s^23) = 3035425.772...
...
T(41) = 12530692681 < 75.(s^82 - 4.s^41) = 12678879361
This shows that the induction step can be applied from n=39 onwards ([(39+3)/2]=21).
Then
T(n) = O(75.(s^(2n) - 4.s^n)) = O(r^n).
(Actually, for all n >= 23, 46.r^n < T(n) < 75.r^n and this is very tight; T(n) = Θ(r^n).)

Understanding "median of medians" algorithm

I want to understand "median of medians" algorithm on the following example:
We have 45 distinct numbers divided into 9 group with 5 elements each.
48 43 38 33 28 23 18 13 8
49 44 39 34 29 24 19 14 9
50 45 40 35 30 25 20 15 10
51 46 41 36 31 26 21 16 53
52 47 42 37 32 27 22 17 54
The first step is sorting every group (in this case they are already sorted)
Second step recursively, find the "true" median of the medians (50 45 40 35 30 25 20 15 10) i.e. the set will be divided into 2 groups:
50 25
45 20
40 15
35 10
30
sorting these 2 groups
30 10
35 15
40 20
45 25
50
the medians is 40 and 15 (in case the numbers are even we took left median)
so the returned value is 15 however "true" median of medians (50 45 40 35 30 25 20 15 10) is 30, moreover there are 5 elements less then 15 which are much less than 30% of 45 which are mentioned in wikipedia
and so T(n) <= T(n/5) + T(7n/10) + O(n) fails.
By the way in the Wikipedia example, I get result of recursion as 36. However, the true median is 47.
So, I think in some cases this recursion may not return true median of medians. I want to understand where is my mistake.
The problem is in the step where you say to find the true median of the medians. In your example, you had these medians:
50 45 40 35 30 25 20 15 10
The true median of this data set is 30, not 15. You don't find this median by splitting the groups into blocks of five and taking the median of those medians, but instead by recursively calling the selection algorithm on this smaller group. The error in your logic is assuming that median of this group is found by splitting the above sequence into two blocks
50 45 40 35 30
and
25 20 15 10
then finding the median of each block. Instead, the median-of-medians algorithm will recursively call itself on the complete data set 50 45 40 35 30 25 20 15 10. Internally, this will split the group into blocks of five and sort them, etc., but it does so to determine the partition point for the partitioning step, and it's in this partitioning step that the recursive call will find the true median of the medians, which in this case will be 30. If you use 30 as the median as the partitioning step in the original algorithm, you do indeed get a very good split as required.
Hope this helps!
Here is the pseudocode for median of medians algorithm (slightly modified to suit your example). The pseudocode in wikipedia fails to portray the inner workings of the selectIdx function call.
I've added comments to the code for explanation.
// L is the array on which median of medians needs to be found.
// k is the expected median position. E.g. first select call might look like:
// select (array, N/2), where 'array' is an array of numbers of length N
select(L,k)
{
if (L has 5 or fewer elements) {
sort L
return the element in the kth position
}
partition L into subsets S[i] of five elements each
(there will be n/5 subsets total).
for (i = 1 to n/5) do
x[i] = select(S[i],3)
M = select({x[i]}, n/10)
// The code to follow ensures that even if M turns out to be the
// smallest/largest value in the array, we'll get the kth smallest
// element in the array
// Partition array into three groups based on their value as
// compared to median M
partition L into L1<M, L2=M, L3>M
// Compare the expected median position k with length of first array L1
// Run recursive select over the array L1 if k is less than length
// of array L1
if (k <= length(L1))
return select(L1,k)
// Check if k falls in L3 array. Recurse accordingly
else if (k > length(L1)+length(L2))
return select(L3,k-length(L1)-length(L2))
// Simply return M since k falls in L2
else return M
}
Taking your example:
The median of medians function will be called over the entire array of 45 elements like (with k = 45/2 = 22):
median = select({48 49 50 51 52 43 44 45 46 47 38 39 40 41 42 33 34 35 36 37 28 29 30 31 32 23 24 25 26 27 18 19 20 21 22 13 14 15 16 17 8 9 10 53 54}, 45/2)
The first time M = select({x[i]}, n/10) is called, array {x[i]} will contain the following numbers: 50 45 40 35 30 20 15 10.
In this call, n = 45, and hence the select function call will be M = select({50 45 40 35 30 20 15 10}, 4)
The second time M = select({x[i]}, n/10) is called, array {x[i]} will contain the following numbers: 40 20.
In this call, n = 9 and hence the call will be M = select({40 20}, 0).
This select call will return and assign the value M = 20.
Now, coming to the point where you had a doubt, we now partition the array L around M = 20 with k = 4.
Remember array L here is: 50 45 40 35 30 20 15 10.
The array will be partitioned into L1, L2 and L3 according to the rules L1 < M, L2 = M and L3 > M. Hence:
L1: 10 15
L2: 20
L3: 30 35 40 45 50
Since k = 4, it's greater than length(L1) + length(L2) = 3. Hence, the search will be continued with the following recursive call now:
return select(L3,k-length(L1)-length(L2))
which translates to:
return select({30 35 40 45 50}, 1)
which will return 30 as a result. (since L has 5 or fewer elements, hence it'll return the element in kth i.e. 1st position in the sorted array, which is 30).
Now, M = 30 will be received in the first select function call over the entire array of 45 elements, and the same partitioning logic which separates the array L around M = 30 will apply to finally get the median of medians.
Phew! I hope I was verbose and clear enough to explain median of medians algorithm.

Finding a set of permutations, with a constraint

I have a set of N^2 numbers and N bins. Each bin is supposed to have N numbers from the set assigned to it. The problem I am facing is finding a set of distributions that map the numbers to the bins, satisfying the constraint, that each pair of numbers can share the same bin only once.
A distribution can nicely be represented by an NxN matrix, in which each row represents a bin. Then the problem is finding a set of permutations of the matrix' elements, in which each pair of numbers shares the same row only once. It's irrelevant which row it is, only that two numbers were both assigned to the same one.
Example set of 3 permutations satisfying the constraint for N=8:
0 1 2 3 4 5 6 7
8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31
32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63
0 8 16 24 32 40 48 56
1 9 17 25 33 41 49 57
2 10 18 26 34 42 50 58
3 11 19 27 35 43 51 59
4 12 20 28 36 44 52 60
5 13 21 29 37 45 53 61
6 14 22 30 38 46 54 62
7 15 23 31 39 47 55 63
0 9 18 27 36 45 54 63
1 10 19 28 37 46 55 56
2 11 20 29 38 47 48 57
3 12 21 30 39 40 49 58
4 13 22 31 32 41 50 59
5 14 23 24 33 42 51 60
6 15 16 25 34 43 52 61
7 8 17 26 35 44 53 62
A permutation that doesn't belong in the above set:
0 10 20 30 32 42 52 62
1 11 21 31 33 43 53 63
2 12 22 24 34 44 54 56
3 13 23 25 35 45 55 57
4 14 16 26 36 46 48 58
5 15 17 27 37 47 49 59
6 8 18 28 38 40 50 60
7 9 19 29 39 41 51 61
Because of multiple collisions with the second permutation, since, for example they're both pairing the numbers 0 and 32 in one row.
Enumerating three is easy, it consists of 1 arbitrary permutation, its transposition and a matrix where the rows are made of the previous matrix' diagonals.
I can't find a way to produce a set consisting of more though. It seems to be either a very complex problem, or a simple problem with an unobvious solution. Either way I'd be thankful if somebody had any ideas how to solve it in reasonable time for the N=8 case, or identified the proper, academic name of the problem, so I could google for it.
In case you were wondering what is it useful for, I'm looking for a scheduling algorithm for a crossbar switch with 8 buffers, which serves traffic to 64 destinations. This part of the scheduling algorithm is input traffic agnostic, and switches cyclically between a number of hardwired destination-buffer mappings. The goal is to have each pair of destination addresses compete for the same buffer only once in the cycling period, and to maximize that period's length. In other words, so that each pair of addresses was competing for the same buffer as seldom as possible.
EDIT:
Here's some code I have.
CODE
It's greedy, it usually terminates after finding the third permutation. But there should exist a set of at least N permutations satisfying the problem.
The alternative would require that choosing permutation I involved looking for permutations (I+1..N), to check if permutation I is part of the solution consisting of the maximal number of permutations. That'd require enumerating all permutations to check at each step, which is prohibitively expensive.
What you want is a combinatorial block design. Using the nomenclature on the linked page, you want designs of size (n^2, n, 1) for maximum k. This will give you n(n+1) permutations, using your nomenclature. This is the maximum theoretically possible by a counting argument (see the explanation in the article for the derivation of b from v, k, and lambda). Such designs exist for n = p^k for some prime p and integer k, using an affine plane. It is conjectured that the only affine planes that exist are of this size. Therefore, if you can select n, maybe this answer will suffice.
However, if instead of the maximum theoretically possible number of permutations, you just want to find a large number (the most you can for a given n^2), I am not sure what the study of these objects is called.
Make a 64 x 64 x 8 array: bool forbidden[i][j][k] which indicates whether the pair (i,j) has appeared in row k. Each time you use the pair (i, j) in the row k, you will set the associated value in this array to one. Note that you will only use the half of this array for which i < j.
To construct a new permutation, start by trying the member 0, and verify that at least seven of forbidden[0][j][0] that are unset. If there are not seven left, increment and try again. Repeat to fill out the rest of the row. Repeat this whole process to fill the entire NxN permutation.
There are probably optimizations you should be able to come up with as you implement this, but this should do pretty well.
Possibly you could reformulate your problem into graph theory. For example, you start with the complete graph with N×N vertices. At each step, you partition the graph into N N-cliques, and then remove all edges used.
For this N=8 case, K64 has 64×63/2 = 2016 edges, and sixty-four lots of K8 have 1792 edges, so your problem may not be impossible :-)
Right, the greedy style doesn't work because you run out of numbers.
It's easy to see that there can't be more than 63 permutations before you violate the constraint. On the 64th, you'll have to pair at least one of the numbers with another its already been paired with. The pigeonhole principle.
In fact, if you use the table of forbidden pairs I suggested earlier, you find that there are a maximum of only N+1 = 9 permutations possible before you run out. The table has N^2 x (N^2-1)/2 = 2016 non-redundant constraints, and each new permutation will create N x (N choose 2) = 28 new pairings. So all the pairings will be used up after 2016/28 = 9 permutations. It seems like realizing that there are so few permutations is the key to solving the problem.
You can generate a list of N permutations numbered n = 0 ... N-1 as
A_ij = (i * N + j + j * n * N) mod N^2
which generates a new permutation by shifting the columns in each permutation. The top row of the nth permutation are the diagonals of the n-1th permutation. EDIT: Oops... this only appears to work when N is prime.
This misses one last permutation, which you can get by transposing the matrix:
A_ij = j * N + i

Resources