code_junkie

Binary search optimization in c?

Nov 12th, 2011
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. typedef struct
  2. {
  3. char key[MAX_KEYLEN];
  4. int rec;
  5. } KeyRecPair;
  6.  
  7. typedef struct
  8. {
  9. KeyRecPair *map;
  10. int numRecs;
  11. } KeyRecMap;
  12.  
  13. int GetRecFromKey(char *key, KeyRecMap *theMap)
  14. {
  15. int cmpValue, bottom = 0;
  16. int half = theMap->numRecs / 2;
  17. int top = theMap->numRecs - 1;
  18.  
  19. while (bottom != top)
  20. {
  21. cmpValue = strncmp(key, theMap->map[half].key, MAX_KEY_LEN);
  22.  
  23. if (cmpValue > 0)
  24. {
  25. /*top stays*/
  26. bottom = half + 1;
  27. half = bottom + (top - bottom) / 2;
  28. continue;
  29. }
  30. if (cmpValue < 0)
  31. {
  32. /*bottom stays*/
  33. top = half - 1;
  34. half = bottom + (top - bottom) / 2;
  35. continue;
  36. }
  37. return theMap->map[half].rec;
  38. }
  39.  
  40. if (0 == strncmp(key, theMap->map[half].key, MAX_KEY_LEN))
  41. return theMap->map[half].rec;
  42. return 0;
  43. }
  44.  
  45. if (cmpValue > 0)
  46. {
  47. /*top stays*/
  48. bottom = half + 1;
  49. half = bottom + (top - bottom) * 3 / 5;
  50. continue;
  51. }
  52. if (cmpValue < 0)
  53. {
  54. /*bottom stays*/
  55. top = half - 1;
  56. half = bottom + (top - bottom) * 2 / 5;
  57. continue;
  58. }
  59.  
  60. ; 30 : if (cmpValue > 0)
  61. test eax, eax
  62. jle SHORT $LN11@GetRecFrom
  63. ; 31 : {
  64. ; omitted inner block for > case.
  65. $LN11@GetRecFrom:
  66. ; 37 : if (cmpValue < 0)
  67. jge SHORT $LN2@GetRecFrom
Add Comment
Please, Sign In to add comment