title: Binary search optimization in c?
body: <p>I am writing a key record look up where the I have an index between the key and the rec number.  This is sorted on the key.  Is there away to do this better that what I have for speed optimization?</p>
  
  <pre><code>typedef struct
  {
      char key[MAX_KEYLEN];
      int  rec;
  } KeyRecPair;
  
  typedef struct
  {
      KeyRecPair *map;
      int         numRecs;
  } KeyRecMap;
  
  int GetRecFromKey(char *key, KeyRecMap *theMap)
  {
      int cmpValue, bottom = 0;
      int half = theMap-&gt;numRecs / 2;
      int top = theMap-&gt;numRecs - 1;
  
      while (bottom != top)
      {
          cmpValue = strncmp(key, theMap-&gt;map[half].key, MAX_KEY_LEN); 
  
          if (cmpValue &gt; 0)
          {
              /*top stays*/
              bottom = half + 1;
              half  = bottom + (top - bottom) / 2;
              continue;
          }
          if (cmpValue &lt; 0)
          {
              /*bottom stays*/
              top = half - 1;
              half  = bottom + (top - bottom) / 2;
              continue;
          }
          return theMap-&gt;map[half].rec;
      }
  
      if (0 == strncmp(key, theMap-&gt;map[half].key, MAX_KEY_LEN))
          return theMap-&gt;map[half].rec;
      return 0;
  }
  </code></pre>