Advertisement
Monika__

bsearch- bez struct, działa

Jun 4th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.13 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. int compareByString(const void* key, const void* element);
  6.  
  7. int compareByInt(const void* key, const void* element);
  8.  
  9. int compereDouble(const void *key, const void *element);
  10.  
  11. void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compare)(const void *, const void *))
  12. {
  13.       const void* currentElement = 0;
  14.     int start = 0;
  15.     int end = nmemb;
  16.     int middle;
  17.     int searchElement;
  18.  
  19.     while (start <= end)
  20.     {
  21.         middle = start + (end - start) / 2;
  22.         currentElement = (char*)base + middle* size;
  23.         searchElement = (*compare)(key, currentElement);
  24.  
  25.         if (searchElement == 0)
  26.         {
  27.             return ((void*)currentElement);
  28.         }
  29.         else if (searchElement < 0)
  30.         {
  31.             end = middle - 1;
  32.         }
  33.         else
  34.         {
  35.             start = middle + 1;
  36.         }
  37.     }
  38.  
  39.     return NULL;
  40. }
  41.  
  42.  
  43. int main (int argc, char *argv[])
  44. {
  45.  
  46.     double *foundDouble = NULL;
  47.     double array[10] = {1.454, 2.2, 3.1343333, 4.34322, 5.4324, 6.7669, 7.9999};
  48.     double searchedDouble = 3.1343333;
  49.     foundDouble = (double*)bsearch(&searchedDouble, array, sizeof(array)/sizeof(double), sizeof(double), compereDouble);
  50.     if (foundDouble == NULL)
  51.     {
  52.         printf("Value not found\n");
  53.     } else {
  54.         printf("found value %f\n", *foundDouble);
  55.     }
  56.     int searchedValue = 3;
  57.     int *foundInt = NULL;
  58.     int arrayInt[10] = {1, 2, 3, 4, 5, 6, 7, 8};
  59.     foundInt = (int*)bsearch(&searchedValue, arrayInt, sizeof(arrayInt)/sizeof(int), sizeof(int), compareByInt);
  60.     if (foundInt == NULL)
  61.     {
  62.         printf("Value not found\n");
  63.     } else {
  64.         printf("found value %d\n", *foundInt);
  65.     }
  66.    
  67.   return 0;
  68. }
  69.  
  70. int compareByString(const void* key, const void* element)
  71. {  
  72.     return strcmp((char *)key, (char *)element);
  73. }  
  74.  
  75.  
  76. int compareByInt(const void* key, const void* element)
  77. {  
  78.     return (*(unsigned char *)key - *(unsigned  char *)element);
  79. }
  80.  
  81. int compereDouble(const void *key, const void *element)
  82. {
  83.     return (*(double*)key - *(double*)element);
  84.  
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement