Domanda

Possible Duplicate:
Can you sort n integers in O(n) amortized complexity?

I have to write an algorithm which, given an unsorted list of integers, returns "the lowest number in the file which exceeds at least 90% of the numbers in the file", or -1 if no such number exists. Simple enough: I sort the list using merge sort, then start at the index 90% of the way along and look for the first number to be larger than the number before it.

Part 2 of the question has got me stumped though. We're given some more information: the integers represent salaries, meaning they're all positive, and the vast majority of them are underneath 1,000,000. Apparently with this extra information it's possible to write an algorithm that solves the original problem in O(n) time, but I haven't the slightest clue how this is possible. Any ideas?

I would post what I've done so far, but I haven't been able to come up with anything whatsoever.

È stato utile?

Soluzione

You are looking for a selection algorithm, which selects the kth largest element in an array. The Wikipedia article gives an O(n) algorithm to do this which is similar to quicksort, but does not sort the entire array, and thus avoids the O(n*logn) runtime.

If the elements are all bounded in a certain range (e.g. 1-1000000 in your case), then another approach is to sort them using counting sort or bucket sort in O(n), and then select the element you need. Since in this case the "vast majority" of elements is under 1000000 rather than all of them, you can perform a bucket sort with 1000001 buckets, and use the last bucket for all elements above 1000000.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top