Here is a way to find the k-th largest number from an ayyay based on the theory of quick sort with an algorithmic complexity of O(n).
First we find a base element from the array randomly, and then reorder the list so that all elements which are greater than the pivot come before the pivot (Sa part) and all elements less than the pivot come after it(Sb part). Now we get two cases:
1. Element number of Sa part is smaller than K, So the answer is the (k-|Sa|)-th number in Sb;
2. If |Sa|>=K, so return the K-th largest number of Sa.
Below is the implementation:
///
<summary>
///
Patition according to quick sort algrithm
///
</summary>
///
<param name="numbers">
numbers array to be parted
</param>
///
<param name="begin">
start subscript
</param>
///
<param name="end">
end subscript
</param>
///
<returns>
partition point
</returns>
public
static
int
Partition(
int
[] numbers,
int
begin,
int
end)
{
int
key
=
numbers[begin];
while
(begin
<
end)
{
while
(begin
<
end
&&
key
>=
numbers[end])
end
--
;
if
(begin
<
end)
numbers[begin]
=
numbers[end];
while
(begin
<
end
&&
key
<=
numbers[begin])
begin
++
;
if
(begin
<
end)
numbers[end]
=
numbers[begin];
}
numbers[begin]
=
key;
return
begin;
}
///
<summary>
///
Get the k-th largest number from an unsorted array
///
</summary>
///
<param name="numbers">
numbers array
</param>
///
<param name="begin">
start subscript
</param>
///
<param name="end">
end subscript
</param>
///
<param name="k">
Point which number to find
</param>
///
<returns>
the k-th largest number
</returns>
public
static
int
GetNumber(
int
[] numbers,
int
begin,
int
end,
int
k)
{
//
Find the partition according to quick-sort algorithm.
int
n
=
Partition(numbers, begin, end);
if
(n
+
1
==
k)
{
return
numbers[n];
}
else
if
(n
+
1
<
k)
{
return
GetNumber(numbers, n
+
1
, end, k);
}
else
{
return
GetNumber(numbers, begin, n
-
1
, k);
}
}
Go to my home page for more posts