Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- int compareByString(const void* key, const void* element);
- int compareByInt(const void* key, const void* element);
- int compereDouble(const void *key, const void *element);
- void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compare)(const void *, const void *))
- {
- const void* currentElement = 0;
- int start = 0;
- int end = nmemb;
- int middle;
- int searchElement;
- while (start <= end)
- {
- middle = start + (end - start) / 2;
- currentElement = (char*)base + middle* size;
- searchElement = (*compare)(key, currentElement);
- if (searchElement == 0)
- {
- return ((void*)currentElement);
- }
- else if (searchElement < 0)
- {
- end = middle - 1;
- }
- else
- {
- start = middle + 1;
- }
- }
- return NULL;
- }
- int main (int argc, char *argv[])
- {
- double *foundDouble = NULL;
- double array[10] = {1.454, 2.2, 3.1343333, 4.34322, 5.4324, 6.7669, 7.9999};
- double searchedDouble = 3.1343333;
- foundDouble = (double*)bsearch(&searchedDouble, array, sizeof(array)/sizeof(double), sizeof(double), compereDouble);
- if (foundDouble == NULL)
- {
- printf("Value not found\n");
- } else {
- printf("found value %f\n", *foundDouble);
- }
- int searchedValue = 3;
- int *foundInt = NULL;
- int arrayInt[10] = {1, 2, 3, 4, 5, 6, 7, 8};
- foundInt = (int*)bsearch(&searchedValue, arrayInt, sizeof(arrayInt)/sizeof(int), sizeof(int), compareByInt);
- if (foundInt == NULL)
- {
- printf("Value not found\n");
- } else {
- printf("found value %d\n", *foundInt);
- }
- return 0;
- }
- int compareByString(const void* key, const void* element)
- {
- return strcmp((char *)key, (char *)element);
- }
- int compareByInt(const void* key, const void* element)
- {
- return (*(unsigned char *)key - *(unsigned char *)element);
- }
- int compereDouble(const void *key, const void *element)
- {
- return (*(double*)key - *(double*)element);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement