Create binary search for integer array - C Data Structure

C examples for Data Structure:Search

Description

Create binary search for integer array

Demo Code

#include <stdio.h>

int binsearch(int x, int v[], int n);

int main(void)
{
    int x = 12, n = 10;
    int v[10] = {2, 3, 4, 10, 11, 12, 14, 18, 20, 21};
    printf("binsearch result: %d\n", binsearch(x, v, n));
    return 0;// w  w  w.  j a v a2 s  . co m
}
//find x in v[0] <= v[1] <= ... <= v[n-1]
int binsearch(int x, int v[], int n){
    int low = 0, high = n - 1, mid;

    while (low < high) {
        mid = (low + high) / 2;
        if (x <= v[mid])
            high = mid;
        else
            low = mid + 1;
    }
    return (x == v[low]) ? low : -1;
}

Result


Related Tutorials