Advertisement
cd62131

binarysearch1 binarysearch2 binarysearch3

Feb 1st, 2019
566
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.25 KB | None | 0 0
  1. #include <stdio.h>
  2. static int binarysearch1(int *a, int n, int key) {
  3.   for (int left = 0, right = n - 1, mid = left + (right - left) / 2;
  4.        left <= right; mid = left + (right - left) / 2) {
  5.     if (key < a[mid]) {
  6.       right = mid - 1;
  7.     } else if (a[mid] < key) {
  8.       left = mid + 1;
  9.     } else {
  10.       return mid;
  11.     }
  12.   }
  13.   return -1;
  14. }
  15. static int binarysearch2(int *a, int n, int key) {
  16.   int i = binarysearch1(a, n, key);
  17.   if (i == -1) {
  18.     return -1;
  19.   }
  20.   for (int j = i; 0 <= j; --j) {
  21.     if (a[j] < key) {
  22.       return j + 1;
  23.     }
  24.   }
  25.   return 0;
  26. }
  27. static int binarysearch3(int *a, int n, int key) {
  28.   for (int left = 0, right = n - 1, mid = left + (right - left) / 2;
  29.        left <= right; mid = (right - left) / 2) {
  30.     if (key < a[mid]) {
  31.       right = mid - 1;
  32.     } else if (a[mid] < key) {
  33.       left = mid + 1;
  34.     } else if (mid == 0 || (0 < mid && a[mid - 1] < key)) {
  35.       return mid;
  36.     } else {
  37.       right = mid - 1;
  38.     }
  39.   }
  40.   return -1;
  41. }
  42. int main(void) {
  43.   int a[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
  44.   size_t n = sizeof(a) / sizeof(a[0]);
  45.   {
  46.     printf("%d\n", binarysearch1(a, n, 1));
  47.     printf("%d\n", binarysearch2(a, n, 1));
  48.     printf("%d\n", binarysearch3(a, n, 1));
  49.   }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement