Như wikipedia nói, trung bình-of-trung vị là về mặt lý thuyết o (N), nhưng nó không được sử dụng trong thực tế vì các nguyên cần thiết của việc tìm kiếm trụ "tốt" làm cho nó quá chậm .
http://en.wikipedia.org/wiki/Selection_algorithm
Đây là nguồn Java cho một thuật toán Quickselect để tìm các yếu tố k'th trong một mảng:
/**
* Returns position of k'th largest element of sub-list.
*
* @param list list to search, whose sub-list may be shuffled before
* returning
* @param lo first element of sub-list in list
* @param hi just after last element of sub-list in list
* @param k
* @return position of k'th largest element of (possibly shuffled) sub-list.
*/
static int select(double[] list, int lo, int hi, int k) {
int n = hi - lo;
if (n < 2)
return lo;
double pivot = list[lo + (k * 7919) % n]; // Pick a random pivot
// Triage list to [<pivot][=pivot][>pivot]
int nLess = 0, nSame = 0, nMore = 0;
int lo3 = lo;
int hi3 = hi;
while (lo3 < hi3) {
double e = list[lo3];
int cmp = compare(e, pivot);
if (cmp < 0) {
nLess++;
lo3++;
} else if (cmp > 0) {
swap(list, lo3, --hi3);
if (nSame > 0)
swap(list, hi3, hi3 + nSame);
nMore++;
} else {
nSame++;
swap(list, lo3, --hi3);
}
}
assert (nSame > 0);
assert (nLess + nSame + nMore == n);
assert (list[lo + nLess] == pivot);
assert (list[hi - nMore - 1] == pivot);
if (k >= n - nMore)
return select(list, hi - nMore, hi, k - nLess - nSame);
else if (k < nLess)
return select(list, lo, lo + nLess, k);
return lo + k;
}
Tôi chưa bao gồm nguồn gốc của sự so sánh và trao đổi phương pháp, vì vậy nó dễ dàng để thay đổi mã để làm việc với Object [] thay vì double [].
Trong thực tế, bạn có thể mong đợi mã trên là o (N).
Nguồn
2014-12-31 23:09:13
bản sao có thể có của [Cách tìm phần tử lớn nhất thứ k trong một mảng chiều dài không được sắp xếp n trong O (n)?] (Http: // stackoverflow .com/questions/251781/how-to-find-the-kth-lớn nhất-yếu tố-in-an-unsorted-array-of-length-n-in-on) –
Hãy nhớ rằng nếu nó có O (nlogn) thì bạn cũng có thể sắp xếp mảng và chia chỉ mục bằng 2. – Zombies
heap xây dựng mất O (n) thời gian không phải O (nlogn) – JerryGoyal