Professional Documents
Culture Documents
Sorting
Bin Sorts
PLSD210
Heap Sort
Slower than quick sort, but guaranteed O(n log n)
Use for real-time systems where time is critical
Sorting
However,
If we can compute an address from the key
(in constant time) then
bin sort algorithms can provide better performance
O(m)
Key
condition
Relax?
36 9 0 25 1 49 64 16 81 4
0
0
1 2
1
81
4 5 6 7
64 25 36
4
16
9
9
49
0
0
1 2
1
81
4 5 6 7
64 25 36
4
16
0
0
9
9
49
0
0
1 2
1
81
4 5 6 7
64 25 36
4
16
0
0
1
9
9
49
Be careful to
add after anything
in the bin already!
0
0
1 2
1
81
4 5 6 7
64 25 36
4
16
0
0
1
9
9
49
8 9
81
0
0
1 2
1
81
4 5 6 7
64 25 36
4
16
0
0
1
9
9
49
6 7 8 9
81
64
0
0
1 2
1
81
4 5 6 7
64 25 36
4
16
0
0
1
4
9
9
49
6 7 8 9
81
64
0
0
1 2
1
81
4 5 6 7
64 25 36
4
16
9
9
49
1 2 3 4 5 6 7 8 9
81
64
0 16 25 36 49
1
4
9
0
0
1 2
1
81
4 5 6 7
64 25 36
4
16
9
9
49
1 2 3 4 5 6 7 8 9
81
64
0 16 25 36 49
1
4
9
How much
space is needed
in each phase?
n items
m bins
Still O(n)
if
struct date {
int day;
/* 1 .. 31 */
int month; /* 1 .. 12 */
int year; /* 0 .. 99 */
}
O( si )
for(j=0;j<n;j++) {
move A[i]
to the end of bin[A[i]->fi]
}
O( n )
for(j=0;j<s[i];j++)
concat bin[j] onto the end of A;
}
O( si )
ith radix
for(j=0;j<s[i];j++)
concat bin[j] onto the end of A;
}
}
O( si )
O( n )
O( si )
O( si )
O( n )
for(j=0;j<s[i];j++)
Move element A[i]
concat bin[j] onto the end of A;
to the end of the bin addressedO(
}
}
si )
into
for(j=0;j<s[i];j++)
concat bin[j] onto the end of A;
}
}
O( si )
O( n )
O( si )
O( si + n ) = O(kn + i=1
si )
i=1
= O(n + si )
i=1
As long as k is constant
In general, if the keys are in (0, bk-1)
Keys are k-digit base-b numbers
si = b for all k
Complexity
O(n+kb) = O(n)
k = log n, si = 2 (say)
log n
log n
i=1
i=1
O( 2 + n ) = O(n log n + 2 )