Data Structures and Algorithms: (CS210/ESO207/ESO211)
Data Structures and Algorithms: (CS210/ESO207/ESO211)
(CS210/ESO207/ESO211)
Lecture 37
Integer Sorting (continued from last lecture)
1
Types of sorting algorithms
In Place Sorting algorithm:
A sorting algorithm which uses only O(1) extra space to sort.
Example: Heap sort, Quick sort.
Stable Sorting algorithm:
A sorting algorithm which preserves the order of equal keys while sorting.
Example: Merge sort.
2
A
0 1 2 3 4 5 6 7
2 5 3 0 6.1 3 7.9 4
A
0 1 2 3 4 5 6 7
0 2 3 3 4 5 6.1 7.9
Integer Sorting algorithms
Continued from last class
Counting sort: algorithm for sorting integers
Input: An array A storing integers in the range [0 ].
Output: Sorted array A.
Running time: O( +) in word RAM model of computation.
Extra space: O( +)
Counting sort: a visual description
A
0 1 2 3 4 5 6 7
Count
0 1 2 3 4 5
2 5 3 0 2 3 0 3
2
2 2 4 7 7 8
0 2 3 0 1
Place
0 1 2 3 4 5
B
0 1 2 3 4 5 6 7
3 0
We could have used Count
array only to output the
elements of A in sorted
order. Why did we compute
Place and B ?
Why did we scan
elements of A in reverse
order (from index to )
while placing them in the final
sorted array B ?
Counting sort: algorithm for sorting integers
CountSort(A[... ], )
For =0 to do Count[] 0;
For =0 to do Count[A[]] Count[A[]] +1;
For =0 to do Place[] Count[];
For =1 to do Place[] Place[ ] + Count[];
For = to do
{ B[ ?? ] A[];
Place[A[]] Place[A[]]-1;
}
return B;
Place[A[]]-1
Counting sort: algorithm for sorting integers
Key points of Counting sort:
It performs arithmetic operations involving O(log + log ) bits (O(1) time in word RAM).
It is a stable sorting algorithm.
Theorem: An array storing integers in the range [.. ]can be sorted in O(+) time and
using total O(+) space in word RAM model.
For , we get an optimal algorithm for sorting.
For =
).
(too bad for > . )
Question:
How to sort integers in the range [..