HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Binary search implementation in C

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
implementationbinarysearch

Problem

int bin_search(int* a, int key)
{
    int lo = 0;
    int hi = sizeof(a)/sizeof(int) - 1;

   while(lo  a[mid]) { lo = mid + 1;}
        else                    return mid;
    }

    return -1;
}


....

for(i = 0; i < sz; ++i)
{
    printf("%d\n", bin_search(a, i));
}


I think that I have a problem with this, but I can't understand why:

int hi = sizeof(a)/sizeof(int) - 1;

Solution

sizeof(a) in this case is sizeof(int*) which is 4 or 8 on most machines. The most simple solution would be passing the length of the input array. Otherwise, your code looks nifty.

Context

StackExchange Code Review Q#105354, answer score: 6

Revisions (0)

No revisions yet.