C examples for Data Structure:Search
Create binary search for integer array
#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; }