On Sep 27, 7:16 am, Eric Sosman <Eric.Sos...@su n.comwrote:
Charlie Gordon wrote On 09/27/07 05:36,:
"Eric Sosman" <Eric.Sos...@su n.coma écrit dans le message de news:
1190818696.4159 40@news1nwk...
For the UINTMAX_MAX'th time, {FLT,DBL,LDBL}_ MIN
are all *positive* values.
The mistake is made so frequently that it must be
easy to make, so let's not make it any easier, okay?
The mistake is made so easily and so frequently that it almost qualifies as
a defect ;-)
The names are just *so* confusing !
They are; something like DBL_SMALLEST might have
avoided confusion. (I'm not heaping scorn on the ANSI
committee for the unfortunate names; I think in this
case the committee just codified "prior art.") But
for now and probably for the life of C we're stuck with
the _MIN names, and must learn to live with them.
Believe it or not, I know better.
Anyway, here is my eventual solution (I sent a copy in to Snippets):
#include <stdlib.h>
/*
"Introducti on to Algorithms"
Cormen, Leiserson, Rivest
pp. 186,187
ISBN: 0-07-013143-0
Simultaneous min & max
using only 3*N/2 comparisons
Written by Dann Corbit
9/25/2007
Donated to the public domain
*/
#ifdef e_type_LONG_DOU BLE
typedef long double e_type;
#elif defined(e_type_ DOUBLE)
typedef double e_type;
#elif defined(e_type_ FLOAT)
typedef float e_type;
#elif defined(e_type_ UNSIGNED_LONG_L ONG)
typedef unsigned long long e_type;
#elif defined(e_type_ LONG_LONG)
typedef long long e_type;
#elif defined(e_type_ UNSIGNED_LONG)
typedef unsigned long e_type;
#elif defined(e_type_ LONG)
typedef long e_type;
#elif defined(e_type_ UNSIGNED)
typedef unsigned e_type;
#elif defined(e_type_ INT)
typedef int e_type;
#elif defined(e_type_ SHORT)
typedef short e_type;
#elif defined(e_type_ UNSIGNED_SHORT)
typedef unsigned e_type;
#elif defined(e_type_ CHAR)
typedef char e_type;
#elif defined(e_type_ UNSIGNED_CHAR)
typedef unsigned char e_type;
#elif defined (__cplusplus)
template < class e_type // works with stl string class etc...
#endif
void minmax(
e_type * a, // input array
size_t arr_size, // array length
e_type * min_e, // smallest thing found
e_type * max_e // biggest thing found
)
{
e_type min_et;
e_type max_et;
size_t i,
n;
if (arr_size % 2) {
min_et = a[0];
max_et = a[0];
n = 1;
} else {
if (a[0] a[1]) {
max_et = a[0];
min_et = a[1];
} else {
min_et = a[0];
max_et = a[1];
}
n = 2;
}
for (i = n; i < arr_size; i += 2) {
if (a[i] a[i + 1]) {
max_et = max_et a[i] ? max_et : a[i];
min_et = min_et < a[i + 1] ? min_et : a[i + 1];
} else {
max_et = max_et a[i + 1] ? max_et : a[i + 1];
min_et = min_et < a[i] ? min_et : a[i];
}
}
*min_e = min_et;
*max_e = max_et;
}
#if defined( UNIT_TEST ) && (defined (e_type_DOUBLE) ||
defined( __cplusplus))
#include <stdio.h>
char string[32767];
double foo[32767];
int main(void)
{
size_t i = 0;
double dmin,
dmax;
while (fgets(string, sizeof string, stdin)) {
foo[i++] = atof(string);
if (i 32766)
break;
}
minmax(foo, i, &dmin, &dmax);
printf("min=%f, max=%f\n", dmin, dmax);
return 0;
}
#endif