Search code examples
calgorithmbinary-search

How would I call a Binary Search function to run?


I am learning C at the moment and was given this code in a book for doing a binary search. I am still very confused on calling a C function with arguments and the book so far hasn't given me much context. I believe the 3rd argument is memory storage (i'm not entirely sure). I tried google/bing but many examples have a main function along with another function which is being called in by main. What am I missing? I tried to call binsearch like I do in Python but i've gotten a bunch of errors.

#include <stdio.h>

/* binsearch: find x in v[0] <= v[1] <= ... <= v[n-1] */

int binsearch(int x, int v[], int n)
{
    int low, high, mid;

    low = 0;
    high = n -1;
    while (low <= high) {
        mid = (low + high)/ 2;
        if (x < v[mid]){
            high = mid -1;
        }
        else if (x > v[mid]) {
            low = mid + 1;
        }
        else{
            // found match
            return mid;
        }
        // no match
        return -1;
    }

}

binsearch(4,[1,2,3,4,5,6,7,8],8)

Thank you.


Solution

  • Basically, you need to do something like this. But as comments recommends, (even though it is easy to skip ahead when we already know some other language) please go back and make sure you pick up the basics of C first.

    int main(){
        int arr[]={1,2,3,4,5,6,7,8};
        int index=binsearch(4,arr,8);   
        printf("Found at index: %d",index);
    }