Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.5 KiB

  1. //+----------------------------------------------------------------------------
  2. //
  3. // File: bsearch.cpp
  4. //
  5. // Module: CMPBK32.DLL
  6. //
  7. // Synopsis: Binary search implementation
  8. //
  9. // Copyright (c) 1997-1998 Microsoft Corporation
  10. //
  11. // Author: quintinb created header 08/17/99
  12. //
  13. //+----------------------------------------------------------------------------
  14. #include "cmmaster.h"
  15. /***
  16. *char *bsearch() - do a binary search on an array
  17. *
  18. *Purpose:
  19. * Does a binary search of a sorted array for a key.
  20. *
  21. *Entry:
  22. * const char *key - key to search for
  23. * const char *base - base of sorted array to search
  24. * unsigned int num - number of elements in array
  25. * unsigned int width - number of bytes per element
  26. * int (*compare)() - pointer to function that compares two array
  27. * elements, returning neg when #1 < #2, pos when #1 > #2, and
  28. * 0 when they are equal. Function is passed pointers to two
  29. * array elements.
  30. *
  31. *Exit:
  32. * if key is found:
  33. * returns pointer to occurrence of key in array
  34. * if key is not found:
  35. * returns NULL
  36. *
  37. *Exceptions:
  38. *
  39. *******************************************************************************/
  40. void * __cdecl CmBSearch (
  41. REG4 const void *key,
  42. const void *base,
  43. size_t num,
  44. size_t width,
  45. int (__cdecl *compare)(const void *, const void *)
  46. )
  47. {
  48. REG1 char *lo = (char *)base;
  49. REG2 char *hi = (char *)base + (num - 1) * width;
  50. REG3 char *mid;
  51. unsigned int half;
  52. int result;
  53. while (lo <= hi)
  54. if (half = num / 2)
  55. {
  56. mid = lo + (num & 1 ? half : (half - 1)) * width;
  57. if (!(result = (*compare)(key,mid)))
  58. return(mid);
  59. else if (result < 0)
  60. {
  61. hi = mid - width;
  62. num = num & 1 ? half : half-1;
  63. }
  64. else {
  65. lo = mid + width;
  66. num = half;
  67. }
  68. }
  69. else if (num)
  70. return((*compare)(key,lo) ? NULL : lo);
  71. else
  72. break;
  73. return(NULL);
  74. }