Fast median search
karpar
posted @ 2008年9月24日 20:12
in
Algorithm
with tags
c median search algo
, 1405 阅读
a asic implementationn
-
#define ELEM_SWAP(a, b) {
-
register elem_type t = (a); (a) = (b); (b) = (t);
-
}
-
-
elem_type quickSelect(elem_type arr[], int n)
-
{
-
int low, high;
-
int median;
-
int middle, ll, hh;
-
-
low = 0;
-
high = n - 1;
-
median = (low + high) / 2;
-
for (; ;)
-
{
-
if (high < low) /* one element only */
-
return arr[median];
-
if (high == low + 1) {
-
/* Two elements only */
-
if (arr[low] > arr[high])
-
ELEM_SWAP(arr[low], arr[high]);
-
return arr[median];
-
}
-
-
/* Find median of low, median and high items; Swap into positin low */
-
middle = (low + high) / 2;
-
if (arr[middle] > arr[high]) ELEM_SWAP(arr[middle], arr[high]);
-
if (arr[low] > arr[high]) ELEM_SWAP(arr[low], arr[high]);
-
if (arr[middle] > arr[low]) ELEM_SWAP(arr[middle], arr[low]);
-
-
/* Swap low item (now in position middle) into low + 1 */
-
ELEM_SWAP(arr[middle], arr[low+1]);
-
-
/* Nibble from each end towards middle, swapping items was stuck */
-
ll = low + 1;
-
hh = high;
-
for (;;)
-
{
-
do ll++; while (arr[low] > arr[ll]);
-
do hh--; while (arr[hh] > arr[low]);
-
-
if (hh < ll) break;
-
ELEM_SWAP(arr[ll], arr[hh]);
-
-
}
-
/* Swap middle item (in position low) back into position */
-
ELEM_SWAP(arr[low], arr[hh]);
-
/* Re-set actieve partition */
-
if (hh <= median)
-
low = ll;
-
if (hh >= median)
-
high = hh - 1;
-
}
-
}
-
-