How to search a word in array of strings using binary search in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

static int compare(const void* a, const void* b) {
    const char* s1 = a;
    const char* const* s2 = b;

    return strcmp(s1, *s2);
}

int main()
{
    const char* arr[] = { "c", "c#", "c++", "go", "java", "javascript", "php", "python", "rust"};

    int size = sizeof(arr) / sizeof(arr[0]);

    char tofind[] = "java";
    char** item = (char*)bsearch(tofind, arr, size, sizeof(arr[0]), compare);

    if (item != NULL) {
        printf("Found item = %s", *item);
    }
    else {
        printf("Item = %s not found", tofind);
    }

    return 0;
}




/*
run:

Found item = java

*/

 



answered May 18, 2023 by avibootz

Related questions

1 answer 120 views
1 answer 228 views
1 answer 63 views
1 answer 171 views
1 answer 146 views
1 answer 191 views
191 views asked Jan 18, 2022 by avibootz
...