little_math
little_math

Reputation: 143

how to find median of 5 sorted list in O(logn) time?

Here is the question:

There are 5 sorted list A,B,C,D,E, which has the same length n. The question is to find an algorithm that can median of this 5 list in O(logn) time. I am thinking of a general idea but I could not figure out the exact complexity it takes.

Assume the median of A,B,C,D,E is a,b,c,d,e. And we have a<b<c<d<e. It is obvious that I could throw away the first half of array A and the last half of array E. Now I have 5 new arrays: B,C,D stay the same, each has n numbers; A' and E' each has n/2 numbers left. I then compute the median of A' and E' as a' and e', compare them to b,c,d. If the new order of 5 medians is a'<b<e'<c<d, then I through away the first half of a' (n/4 numbers) and the last n/4 numbers of array D, because we need to throw away equal numbers on both sides of the final median. The process continue...

I have a kind of feeling that the algorithm is O(logn). But I don't know the exact proof. In the first logn steps, we can surely reduce the candidate numbers to 3n, adding up all the remaining numbers of the 5 lists. The first time we kick out n numbers, the second time at least n/2 numbers, the third time n/4 numbers and so on. However, I don't know how to analysis after I get 3n remaining numbers.

Can this algorithm actually give me O(logn)?

Upvotes: 3

Views: 2145

Answers (1)

OleGG
OleGG

Reputation: 8657

Yes, it actually can. Just look at those statements

  • We can get final result only if we have one list. Unless we have at least two lists, we can't speak about this.
  • Every step of algorithm we're cutting by half two of lists. If there is only one element in list, we're deleting whole list.
  • Let's count, how many steps take it to delete the list. On first deletion we'll delete n/2 items, an second - n/4 and so on till one element left, when we're finally deleting the list. It will take about log(n) operations (don't know if it's really log(n) or log(n)+1 but in both cases it is O(log(n)) ).
  • So, we need to eliminate 5 lists (operation of finding median in last list can be generalized to operation of reducing lists). It takes O(log(n)) to eliminate one of them, so we'll do all the stuff also in O(log(n)), cause 5 is constant.

Upvotes: 2

Related Questions