Lecture 09 Ticket Solution
Complete before the beginning of class on Wednesday, 09/21
-
Suppose \(a\) is an array of binary values of size \(n\). That is, for every index \(i\), we \(a[i] = 0\) or \(1\). Give pseudocode for a procedure that sorts \(a\) in \(O(n)\) time.
-
Each row below represents a 12-bit binary integer (where the right most bit is the 1s bit, etc). Sort the list of numbers in ascending order.
1
2
3
4
5
6
7
8
9
110110100110
100110001001
001000101000
101100111001
000010001010
111100011100
101111001100
010100010010
011011100010
Solution
- Consider the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
BinarySort(a):
i <- 1
j <- size(a)
while i < j do:
if a[i] = 1 and a[j] = 0 then
swap(a, i j)
i <- i+1
j <- j-1
else
if a[i] = 0 then i <- i+1
if a[j] = 1 then j <- j-1
endif
endwhile
- Here’s a sorted list:
1
2
3
4
5
6
7
8
9
111100011100
110110100110
101111001100
101100111001
100110001001
011011100010
010100010010
001000101000
000010001010