Binary Search

    0

    0

    Giovanny Gongora

    Codiga's C Recipes

    Binary Search Implementation

    #include <stdio.h>
    #include <stdlib.h>
    
    int binarySearch(int *A, int n, int key) {
    	int p = 0, q, r = (n-1);
    	while (p < r) {
    		q = (p + r) / 2;
    		if (key == *(A + q)) {
    			return q;
    		}
    		else if (key > *(A + q)) {
    			p = q + 1;
    		}
    		else {
    			r = q - 1;
    		}
    	}
    	return -1;
    }
    
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Explore
    • Cookbooks
    • Playground
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.