codegurukool.com · Free coding tutorials & online compiler

Home › C Tutorial › C searching (DSA)

C searching (DSA)

Linear and binary search.

Linear search checks each item. Binary search halves a sorted array each step, so it is much faster on big data.

Example code

#include <stdio.h>
int bsearch2(int a[], int n, int t) {
  int lo = 0, hi = n - 1;
  while (lo <= hi) {
    int m = (lo + hi) / 2;
    if (a[m] == t) return m;
    if (a[m] < t) lo = m + 1; else hi = m - 1;
  }
  return -1;
}
int main() {
  int a[] = {1, 3, 5, 7, 9};
  printf("%d\n", bsearch2(a, 5, 7));
  return 0;
}

Run this code in the online editor

← C command-line argumentsC sorting (DSA) →