Advertisement
ppupil2

binary-searches

Mar 24th, 2020
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.84 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4.  
  5. /*  binary Find returns the first index where search == key[index] for key[size] where key is sorted in
  6.     ASCENDING ORDER
  7.     or -1 if match not found
  8. */
  9.  
  10. int binaryFind (int search, int key[], int size) {
  11.     int rc = -1, i, low = 0, high = size-1;
  12.  
  13.     do {
  14.         /* calculate mid-element */
  15.         i = (low + high + 1) / 2;
  16.         if (search < key[i]) {
  17.             /* reset high element */
  18.             high = i - 1;
  19.         }        
  20.         else if (search > key[i]) {
  21.             /* reset low element */
  22.             low = i + 1;
  23.         }
  24.         else {
  25.             /* found it */
  26.             rc = i;
  27.         }
  28.     } while (rc == -1 && low <= high);
  29.      
  30.     return rc;
  31. }
  32.  
  33. int main() {
  34.     int a[7] = {1, 2, 3, 4, 5, 76, 413}, x;
  35.    
  36.     x = binaryFind(76, a, 7);
  37.     if (x != -1) {
  38.         printf("Found 76 in position number %d.", x+1);
  39.     }
  40.     else printf("76 is not found.");
  41.    
  42.     return (0);
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement