1

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
1.3 kB
2
Indexable
Never
#include <stdio.h>

int arr[15] = {0};

int BinarySearch(lowb, highb, key) {
    int mid;
    mid = lowb + (highb - lowb) / 2;

    if (lowb >= highb) return -1;

    for (int i = 0; i < 15; i++) {
        if (i < lowb || i > highb) {
            printf("     ");
        }
        else if (i == mid) {
            printf("%5d*", arr[mid]);
        }
        else {
            if (i == mid + 1) printf("%4d", arr[i]);
            else printf("%5d", arr[i]);
        }
    }
    printf("\n");

    if (arr[mid] == key) return mid;
    else if (key > arr[mid]) {
        return BinarySearch(mid+1, highb, key);
    }
    else return BinarySearch(lowb, mid-1, key);
}

int main() {
    int key;

    int ans;

    printf("Enter a number between 0 and 28: ");
    scanf("%d", &key);

    printf("Subscripts:\n");
    for (int i = 0; i < 15; i++) {
        printf("%5d", i);
    }
    printf("\n");
    for (int i = 0; i < 15; i++) {
        printf("-----");
    }
    printf("\n");

    for (int i = 0; i < 15; i++) {
        arr[i] = i*2;
    }

    ans = BinarySearch(0, 14, key);

    if (ans == -1) {
        printf("%d not found\n", key);
    }
    else printf("%d found in array element %d\n", key, ans);

    return 0;
}