#include <stdio.h>
char *input_argv[] = { "prog.c", "11", "5", "7", "11", "22" }; // al posto di argv[]
int input_argc = sizeof (input_argv) / sizeof (input_argv[0]); // al posto di argc
int
ricercabin (int lista[], int x, int a, int z)
{
int m;
// Determina l'elemento centrale.
m = (a + z) / 2;
if (m < a)
{
// Non restano elementi da controllare: l'elemento
// cercato non c'รจ.
return -1;
}
else if (x < lista[m])
{
// Si ripete la ricerca nella parte inferiore.
return ricercabin (lista, x, a, m-1);
}
else if (x > lista[m])
{
// Si ripete la ricerca nella parte superiore.
return ricercabin (lista, x, m+1, z);
}
else
{
// La variabile m rappresenta l'indice dell'elemento
// cercato.
return m;
}
}
int main (int argc, char *argv[])
{
int lista[input_argc - 2];
int x;
int i;
// Acquisisce il primo argomento come valore da cercare.
sscanf (input_argv
[1], "%i", &x
);
// Considera gli argomenti successivi come gli elementi
// dell'array da scandire.
for (i = 2; i < input_argc; i++)
{
sscanf (input_argv
[i
], "%i", &lista
[i
-2]); }
// Esegue la ricerca.
i = ricercabin (lista, x, 0, input_argc-2);
// Emette il risultato.
printf ("%i si trova nella posizione %i\n", x
, i
);
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CgpjaGFyICppbnB1dF9hcmd2W10gPSB7ICJwcm9nLmMiLCAiMTEiLCAiNSIsICI3IiwgIjExIiwgIjIyIiB9OyAgICAgIC8vIGFsIHBvc3RvIGRpIGFyZ3ZbXQppbnQgICBpbnB1dF9hcmdjICAgPSBzaXplb2YgKGlucHV0X2FyZ3YpIC8gc2l6ZW9mIChpbnB1dF9hcmd2WzBdKTsgIC8vIGFsIHBvc3RvIGRpIGFyZ2MKCmludApyaWNlcmNhYmluIChpbnQgbGlzdGFbXSwgaW50IHgsIGludCBhLCBpbnQgeikKewogICAgaW50IG07CgogICAgLy8gRGV0ZXJtaW5hIGwnZWxlbWVudG8gY2VudHJhbGUuCgogICAgbSA9IChhICsgeikgLyAyOwoKICAgIGlmIChtIDwgYSkKICAgICAgewogICAgICAgIC8v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