Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

algorithm - How to sort a 0/1 array with 2n/3 comparisons?

In Algorithm Design Manual, there is such an excise

4-26 Consider the problem of sorting a sequence of n 0’s and 1’s using comparisons. For each comparison of two values x and y, the algorithm learns which of x < y, x = y, or x > y holds.

(a) Give an algorithm to sort in n − 1 comparisons in the worst case. Show that your algorithm is optimal.

(b) Give an algorithm to sort in 2n/3 comparisons in the average case (assuming each of the n inputs is 0 or 1 with equal probability). Show that your algorithm is optimal.

For (a), I think it is fairly easy. I can choose a[n-1] as pivot, then do something like in quicksort partition, scan 0 to n - 2, find the middle point where left side is all 0 and right side is all 1, this take n - 1 comparisons.

But for (b), I can't get a clue. It says "each of the n inputs is 0 or 1 with equal probability", so I guess I can assume the numbers of 0 and 1 equal? But how can I get a result which is related to 1/3? divide the whole array into 3 groups?

Thanks

like image 294
Jackson Tale Avatar asked Apr 01 '12 14:04

Jackson Tale


People also ask

Which sorting technique will you use to sort an already sorted array with only 2 middle numbers unsorted should be efficient?

We can use Insertion Sort to sort the elements efficiently.

How do you find the number of comparisons in sorting?

In general, the average number of comparisons per pass in selection sort will always be one half of the number of items to be sorted. For eight items, we have 1/2(82 + 8) = 1/2(64 + 8) = 1/2(72) = 36 comparisons.

Which sorting algorithm is best if the list is already sorted why?

Insertion sort runs much more efficiently if the array is already sorted or "close to sorted."

What is the best sorting algorithm to use for the elements in array are more than 1 million in general?

What is the best sorting algorithm to use for the elements in array are more than 1 million in general? (A) Merge sort.


Video Answer


1 Answers

"0 or 1 with equal probability" is the condition for "average" case. Other cases may have worse timing.

Hint 1: 2/3 = 1/2 + 1/8 + 1/32 + 1/128 + ...

Hint 2: Consider the sequence as a sequence of pairs and compare the items in each pair. Half will return equal; half will not. Of the half that are unequal you know which item in the pair is 0 and which is 1, so those need no more comparisons.

like image 137
xan Avatar answered Oct 26 '22 16:10

xan