Re: binary search



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


.



Relevant Pages

  • [PATCH 7/9] kconfig: simplify symbol type parsing
    ... int token; ... struct symbol *symbol; ... struct expr *expr; ... static const unsigned short int yyrline= ...
    (Linux-Kernel)
  • Re: Is there any way to hack around C#s lack of support for optional arguments?
    ... >Is it totally fruitless to try to deal with optional arguments? ... >imagine an interface that omits the OPTIONAL keyword but simply documents ... change the parameter types to IntPtr or int*. ...
    (microsoft.public.dotnet.framework.interop)
  • binary search
    ... I'm trying to do simple implementation of 'binary search' algorithm. ... static const double power= { ... static int b_search(const double data, double value, double low, double ...
    (comp.lang.c)
  • Re: Is there any way to hack around C#s lack of support for optional arguments?
    ... There's also a couple of functions for dealing with variants ... > addresses and lets you write values into them without using unsafe code. ... >> change the parameter types to IntPtr or int*. ...
    (microsoft.public.dotnet.framework.interop)
  • Re: Component help
    ... First of all, after what you said, I switched the parameter types to long and ... while they were still int when I tried to call it with ... dim object, res ... I then checked under the Visual Studio object browser and it had the ...
    (microsoft.public.win32.programmer.ole)