算法导论 chapter7 线性排序
counting sort: for A[1,...,n], given that for any i, 0<=i<=n, then c<=A[i]<=d. let m = d-c+1, create an array B[1, ..., m]. each item B[j] means how many items in A are less or equal to c+j-1:
for i <- 1 to n
B[A[i]]++
for j <- 2 to m
B[j] = B[j] + B[j-1]
then it's easy to construct the ordered sequence using B.
this is a O(n) algothrim
radix sort: sort each digit of all the numbers. eg, sort by the single digit, then sort by the tens digit...
each time's sort is a counting sort, it's O(n)
so radix sort is also O(n)
bucket sort :assumes that the input is an n-element array A and that each element A[i] in the array satisfies 0 ≤ A[i] < 1. The code requires an auxiliary array B[0 ‥ n - 1] of linked lists (buckets) and assumes that there is a mechanism for maintaining such lists.
BUCKET-SORT(A)
1 n ← length[A]
2 for i ← 1 to n
3 do insert A[i] into list B[⌊n A[i]⌋]
4 for i ← 0 to n - 1
5 do sort list B[i] with insertion sort
6 concatenate the lists B[0], B[1], . . ., B[n - 1] together in order
Problems 8-3: Sorting variable-length items
-
You are given an array of integers, where different integers may have different numbers of digits, but the total number of digits over all the integers in the array is n. Show how to sort the array in O(n) time.
-
You are given an array of strings, where different strings may have different numbers of characters, but the total number of characters over all the strings is n. Show how to sort the strings in O(n) time.
answer:
a. totally n digits means at most n numbers. using radix sort, easy to get O(n)
b. the same as a
Suppose that you are given n red and n blue water jugs, all of different shapes and sizes. All red jugs hold different amounts of water, as do the blue ones. Moreover, for every red jug, there is a blue jug that holds the same amount of water, and vice versa.
It is your task to find a grouping of the jugs into pairs of red and blue jugs that hold the same amount of water. To do so, you may perform the following operation: pick a pair of jugs in which one is red and one is blue, fill the red jug with water, and then pour the water into the blue jug. This operation will tell you whether the red or the blue jug can hold more water, or if they are of the same volume. Assume that such a comparison takes one time unit. Your goal is to find an algorithm that makes a minimum number of comparisons to determine the grouping. Remember that you may not directly compare two red jugs or two blue jugs.
-
Describe a deterministic algorithm that uses Θ(n2) comparisons to group the jugs into pairs.
-
Prove a lower bound of Θ(n lg n) for the number of comparisons an algorithm solving this problem must make.
-
Give a randomized algorithm whose expected number of comparisons is O(n lg n), and prove that this bound is correct. What is the worst-case number of comparisons for your algorithm?
a.
posted on 2011-06-01 11:35 freestyleking 阅读(600) 评论(0) 编辑 收藏 举报