Sorting Algorithms
Sorting Algorithms
Sorting by counting
Let’s assume that the value range of the keys is small, atmost
the same range than the amount of the elements.
• For simplicity we assume that the keys of the elements are
from the set {1, 2, . . . , k}, and k = O(n).
• The amount of elements with each given key is calculated.
• Based on the result the elements are placed directly into
their correct positions.
TIE-20106 4
C OUNTING -S ORT(A, B, k)
1 for i := 1 to k do
2 C[i] := 0 (initialize a temp array C with zero)
3 for j := 1 to A.length do
4 C[A[j].key] := C[A[j].key] + 1 (calculate the amount of elements with key = i)
5 for i := 2 to k do
6 C[i] := C[i] + C[i − 1] (calculate how many keys ≤ i)
7 for j := A.length downto 1 do (scan the array from end to beginning)
8 B[C[A[j].key]] := A[j] (place the element into the output array)
9 C[A[j].key] := C[A[j].key] − 1 (the next correct location is a step to the left)
Running-time:
• The first and the third for-loop take Θ(k) time.
• The second and the last for-loop take Θ(n) time.
⇒ The running time is Θ(n + k).
• If k = O(n), the running-time is Θ(n).
• All basic operations are simple and there are only a few of
them in each loop so the constant coefficient is also small.
Bucket sort
Let’s assume that the keys are within a known range of values
and the key values are evenly distributed.
• Each key is just as probable.
• For the sake of an example we’ll assume that the key values
are between zero and one.
• Let’s use n buckets B[0] . . . B[n − 1].
B UCKET-S ORT(A)
1 n := A.length
2 for i := 1 to n do (go through the elements)
3 I NSERT(B[bn · A[i]c], A[i]) (throw the element into the correct bucket)
4 k := 1 (start filling the array from index 1)
5 for i := 0 to n − 1 do (go through the buckets)
6 while B[i] not empty do (empty non-empty buckets...)
7 A[k] := E XTRACT-M IN(B[i]) (... by moving the elements, smallest first...)
8 k := k + 1 (... into the correct location in the result array)
TIE-20106 14
Example: contacts
• operations
– finding a phonenumber based on the
name
– adding a new contact into the phone-
book
– removing a contact and all the related
information
• assumptions
– additions and removals are needed
rarely
– phonenumber queries are done often
– additions and removals are done in
groups
TIE-20106 24