kusano 7d535a
kusano 7d535a
/*! @file qselect.c
kusano 7d535a
 * \brief Quickselect: returns the k-th (zero-based) largest value in A[].
kusano 7d535a
 *
kusano 7d535a
 * 
kusano 7d535a
 * -- SuperLU routine (version 4.1) --
kusano 7d535a
 * Lawrence Berkeley National Laboratory.
kusano 7d535a
 * November, 2010
kusano 7d535a
 * 
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
#include "slu_ddefs.h"
kusano 7d535a
kusano 7d535a
double dqselect(int n, double A[], int k)
kusano 7d535a
{
kusano 7d535a
    register int i, j, p;
kusano 7d535a
    register double val;
kusano 7d535a
kusano 7d535a
    k = SUPERLU_MAX(k, 0);
kusano 7d535a
    k = SUPERLU_MIN(k, n - 1);
kusano 7d535a
    while (n > 1)
kusano 7d535a
    {
kusano 7d535a
	i = 0; j = n-1;
kusano 7d535a
	p = j; val = A[p];
kusano 7d535a
	while (i < j)
kusano 7d535a
	{
kusano 7d535a
	    for (; A[i] >= val && i < p; i++);
kusano 7d535a
	    if (A[i] < val) { A[p] = A[i]; p = i; }
kusano 7d535a
	    for (; A[j] <= val && j > p; j--);
kusano 7d535a
	    if (A[j] > val) { A[p] = A[j]; p = j; }
kusano 7d535a
	}
kusano 7d535a
	A[p] = val;
kusano 7d535a
	if (p == k) return val;
kusano 7d535a
	else if (p > k) n = p;
kusano 7d535a
	else
kusano 7d535a
	{
kusano 7d535a
	    p++;
kusano 7d535a
	    n -= p; A += p; k -= p;
kusano 7d535a
	}
kusano 7d535a
    }
kusano 7d535a
kusano 7d535a
    return A[0];
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
float sqselect(int n, float A[], int k)
kusano 7d535a
{
kusano 7d535a
    register int i, j, p;
kusano 7d535a
    register float val;
kusano 7d535a
kusano 7d535a
    k = SUPERLU_MAX(k, 0);
kusano 7d535a
    k = SUPERLU_MIN(k, n - 1);
kusano 7d535a
    while (n > 1)
kusano 7d535a
    {
kusano 7d535a
	i = 0; j = n-1;
kusano 7d535a
	p = j; val = A[p];
kusano 7d535a
	while (i < j)
kusano 7d535a
	{
kusano 7d535a
	    for (; A[i] >= val && i < p; i++);
kusano 7d535a
	    if (A[i] < val) { A[p] = A[i]; p = i; }
kusano 7d535a
	    for (; A[j] <= val && j > p; j--);
kusano 7d535a
	    if (A[j] > val) { A[p] = A[j]; p = j; }
kusano 7d535a
	}
kusano 7d535a
	A[p] = val;
kusano 7d535a
	if (p == k) return val;
kusano 7d535a
	else if (p > k) n = p;
kusano 7d535a
	else
kusano 7d535a
	{
kusano 7d535a
	    p++;
kusano 7d535a
	    n -= p; A += p; k -= p;
kusano 7d535a
	}
kusano 7d535a
    }
kusano 7d535a
kusano 7d535a
    return A[0];
kusano 7d535a
}