
/* Greg Klanderman  Spring 1991 */


/******** my rank order select code for the rank ordering ******/
/* this procedure returns the element that will be in position */
/* *n if the array from *i to *j were sorted, avg case O(n) time */
/* this procedure is pretty much out of AHU, but being a hacker */
/* I've made it as fast as possible */
/* I make use of the fact that this procedure is tail recursive */

long select(register long *i,	/* ptr to array begining */
	    register long *j, 	/* ptr to array end */
	    register long *n)	/* ptr to elem we want when sorted */
{
  register long pivot;
  register long *k;
  register long *l;
  register long tmp;

  while (1)
  {					/* find pivot:not the smallest elem */
    pivot = *i;

    for (k = i + 1; k <= j; k++)
    {
      if ((tmp = *k) > pivot)
      {
	pivot = tmp;			/* use *k */
	goto partition;
      }
      else if (tmp < pivot)
	goto partition;			/* use *i */
    }

    return (pivot);	/* *i *//* all values are the same so return any one */


partition:				/* do partition */
    l = j;
    k = i;

    do {
      tmp = *l;				/* swap */
      *l = *k;
      *k = tmp;

      while (*k < pivot)	k++;
      while (*l >= pivot)	l--;
    } while (k <= l);

    if (n < k)      j = l;		/* return (select(i, k-1, n)); */
    else	    i = k;		/* return (select(k, j, n)); */
  }					/* end of while */
}


