Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- static int binarysearch1(int *a, int n, int key) {
- for (int left = 0, right = n - 1, mid = left + (right - left) / 2;
- left <= right; mid = left + (right - left) / 2) {
- if (key < a[mid]) {
- right = mid - 1;
- } else if (a[mid] < key) {
- left = mid + 1;
- } else {
- return mid;
- }
- }
- return -1;
- }
- static int binarysearch2(int *a, int n, int key) {
- int i = binarysearch1(a, n, key);
- if (i == -1) {
- return -1;
- }
- for (int j = i; 0 <= j; --j) {
- if (a[j] < key) {
- return j + 1;
- }
- }
- return 0;
- }
- static int binarysearch3(int *a, int n, int key) {
- for (int left = 0, right = n - 1, mid = left + (right - left) / 2;
- left <= right; mid = (right - left) / 2) {
- if (key < a[mid]) {
- right = mid - 1;
- } else if (a[mid] < key) {
- left = mid + 1;
- } else if (mid == 0 || (0 < mid && a[mid - 1] < key)) {
- return mid;
- } else {
- right = mid - 1;
- }
- }
- return -1;
- }
- int main(void) {
- int a[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
- size_t n = sizeof(a) / sizeof(a[0]);
- {
- printf("%d\n", binarysearch1(a, n, 1));
- printf("%d\n", binarysearch2(a, n, 1));
- printf("%d\n", binarysearch3(a, n, 1));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement