Re: binary search
- From: "Roman Mashak" <mrv@xxxxxxxx>
- Date: Thu, 29 Nov 2007 18:50:25 -0800
Hello, CBFalconer!
You wrote on Thu, 29 Nov 2007 00:13:00 -0500:
[skip]
Thank you for your suggestions.
??>> int main(void)
??>> {
??>> b_search(power, -97.0, -100.0, -85.0);
C> ^ ...... ^
C> I think these want to be 0 and 15, and the parameter types should
C> be size_t.
Do you mean 'low' and 'high' parameters should have 'size_t' type?
??>> return 0;
??>> }
??>>
??>> It's compiled correctly, but I doubt I'm passing array as parameter
??>> in a right way (what is more correct?). And second, considering
??>> that values in array are negative, 'mean' is calculated wrong
??>> ((-100 + (-85)) / 2 = -92.5), or I'm not understanding the algorithm?
C> The latter, causing the first.
This is my last version, and I tried a non-recursive algorithm:
#include <stdio.h>
#include <stdint.h>
#define MAX 16
/* array of power values */
static const double power[MAX] = {
-100.0, -99.0, -98.0, -97.0, -96.0, -95.0, -94.0, -93.0,
-92.0, -91.0, -90.0, -89.0, -88.0, -87.0, -86.0, -85.0
};
static double b_search(const double data[], double value)
{
uint16_t low = 0;
uint16_t high = MAX - 1;
uint16_t mean;
while (low <= high) {
mean = (low + high) / 2;
if (data[mean] > value)
high = mean - 1;
else if (data[mean] < value)
low = mean + 1;
else
return data[mean];
}
return -1.0;
}
int main(void)
{
double res = b_search(power, -86.0);
return 0;
}
Is it fine now?
With best regards, Roman Mashak. E-mail: mrv@xxxxxxxx
.
- Follow-Ups:
- Re: binary search
- From: Kaz Kylheku
- Re: binary search
- References:
- binary search
- From: Roman Mashak
- Re: binary search
- From: CBFalconer
- binary search
- Prev by Date: Re: New language features?
- Next by Date: Re: Reading a table
- Previous by thread: Re: binary search
- Next by thread: Re: binary search
- Index(es):
Relevant Pages
|