Question 1
Merging with smaller auxiliary array. Suppose that the subarray a[0] to a[N-1] is sorted and the subarray a[N] to a[2*N-1] is sorted. How can you merge the two subarrays
so that a[0] to a[2*N-1] is sorted using an auxiliary array of size N (instead
of 2N)?
Your Answer |
|
Score |
Explanation |
---|
Total |
|
0.00 / 0.00 |
|
Question Explanation
Hint: copy only the left half into the auxiliary array.
Question 2
Counting inversions. An inversion in an array a[] is
a pair of entries a[i] and a[j] such
that i<j but a[i]>a[j].
Given an array, design a linearithmic algorithm to count the number of inversions.
Your Answer |
|
Score |
Explanation |
---|
Total |
|
0.00 / 0.00 |
|
Question Explanation
Hint: count while mergesorting.
Question 3
Shuffling a linked list. Given a singly-linked list containing N items,
rearrange the items uniformly at random. Your algorithm should consume a logarithmic (or constant) amount of extra memory and run in time proportional to NlogN in
the worst case.
Your Answer |
|
Score |
Explanation |
---|
Total |
|
0.00 / 0.00 |
|
Question Explanation
Hint: design a linear-time subroutine that can take two uniformly shuffled linked lists of sizes N1 and N2 and
combined them into a uniformly shuffled linked lists of size N1+N2.
類似歸併排序,從1-2-4,
保證兩個歸併前是隨機排序的,即N1和N2裏的元素都有 1/N1 和 1/N2 的概率排到每一個位置,那麼N1和N2歸併的時候,N1/(N1+N2)的概率選擇N1,N2/(N1+N2)的概率選擇N2,那麼每個元素在每個位置的概率都是1/(N1+N2)。例如,兩個長度爲1的歸併,每個都有1/2的概率排在兩個位置上。