16. 1 2 3 4 5 6 7 8 9
816425 3616 49
Sorting - Generalised Bin Sort
Radix sort - Bin sort trong c叩c giai o畉n
Giai o畉n 1 S畉p x畉p d畛a vo s畛 c坦 箪 ngh挑a t畛i thi畛u
Giai o畉n 2 S畉p x畉p d畛a vo ph畉n l畛n s畛 c坦 箪 ngh挑a
0 1 2 3 4 5 6 7 8 9
0 1
81
64
4
25 36
16
9
49
0
0
1
4
9
Kh担ng gian c畉n
thi畉t cho m畛i
giai o畉n
l bao nhi棚u?
n items
m bins
17. Sorting T畛ng qu叩t c畛a Bin Sort
Radix sort Ph但n t鱈ch
Giai o畉n 1 S畉p x畉p d畛a vo s畛 c坦 箪 ngh挑a t畛i thi畛u
T畉o m bins O(m)
C畉p ph叩t n items O(n)
Giai o畉n 2
T畉o m bins O(m)
C畉p ph叩t n items O(n)
Cu畛i c湛ng
Li棚n k畉t m bins O(m)
T畉t c畉 c叩c b動畛c th畛c hi畛n tu畉n t畛, v狸 th畉 b畛 xung
T畛ng O(3m+2n) O(m+n) O(n) cho m<<n
18. Sorting - Radix Sort Ph但n t鱈ch
Radix sort T畛ng qu叩t
V畛 c董 b畉n: m畛i giai o畉n c坦 th畛 ph湛 h畛p v畛i c叩c ki畛u
d畛 li畛u kh叩c nhau.
C叩c s畛 nguy棚n
C叩c gi叩 tr畛 c董 s畛 10, 16, 100,
C叩c thnh ph畉n d畛 li畛u kh担ng c湛ng ki畛u d畛 li畛u
V畉n l O(n) n畉u n >> si v畛i m畛i i
struct date {
int day; /* 1 .. 31 */
int month; /* 1 .. 12 */
int year; /* 0 .. 99 */
}
G 1 - s1=31 bins
G 2 - s2=12 bins
G 3 - s3=100 bins
19. Radix Sort - Analysis
Generalised Radix Sort Algorithm
radixsort( A, n ) {
for(i=0;i<k;i++) {
for(j=0;j<s[i];j++) bin[j] = EMPTY;
for(j=0;j<n;j++) {
move A[i]
to the end of bin[A[i]->fi]
}
for(j=0;j<s[i];j++)
concat bin[j] onto the end of A;
}
}
O( si )
O( n )
O( si )
For each of k radices
20. Radix Sort - Analysis
Generalised Radix Sort Algorithm
radixsort( A, n ) {
for(i=0;i<k;i++) {
for(j=0;j<s[i];j++) bin[j] = EMPTY;
for(j=0;j<n;j++) {
move A[i]
to the end of bin[A[i]->fi]
}
for(j=0;j<s[i];j++)
concat bin[j] onto the end of A;
}
}
O( si )
O( n )
O( si )
Clear the si bins for the ith radix
21. Radix Sort - Analysis
Generalised Radix Sort Algorithm
radixsort( A, n ) {
for(i=0;i<k;i++) {
for(j=0;j<s[i];j++) bin[j] = EMPTY;
for(j=0;j<n;j++) {
move A[i]
to the end of bin[A[i]->fi]
}
for(j=0;j<s[i];j++)
concat bin[j] onto the end of A;
}
}
O( si )
O( n )
O( si )
Move element A[i]
to the end of the bin addressed
by the ith field of A[i]
22. Radix Sort - Analysis
Generalised Radix Sort Algorithm
radixsort( A, n ) {
for(i=0;i<k;i++) {
for(j=0;j<s[i];j++) bin[j] = EMPTY;
for(j=0;j<n;j++) {
move A[i]
to the end of bin[A[i]->fi]
}
for(j=0;j<s[i];j++)
concat bin[j] onto the end of A;
}
}
O( si )
O( n )
O( si )
Concatenate si bins into
one list again
23. Radix Sort Ph但n t鱈ch
Total
k v嘆ng l畉p, 2si + n cho m畛i v嘆ng
Nh動 v畉y k l m畛t h畉ng s畛
T畛ng qu叩t, N畉u keys thu畛c (0, bk-1)
Keys l nh畛ng s畛 k-digit base-b
si = b for all k
畛 ph畛c t畉p O(n+kb) = O(n)
O( si + n ) = O(kn + si )
= O(n + si )
i=1
i=1 i=1
k
kk