In C, Binary Search A Number In Array

#include<stdio.h>

void sort(int*, const int);
int binary_search(int*, const int, const int);

void main(){
    int my_numbers[] = { 2430,4719,2247,1397, 155,2401,3015,2324, 670,2134, 469, 952,3881,3633,3459,4366, 19, 935,1610, 724, 4373,2111,4542,1596,4244,4822,4964,1504, 462, 652, 1561,4557,4791, 387, 522 ,513,4872,4569, 241,2662, 3241,2475,3664,4028,2064,3993, 572, 649, 418,3283, 4347,3207,3349, 100,3651,4194,4725,1276,1244, 722, 2019,1232,3491, 606, 261,2054,3699,3901,1471,4477, 1569, 438,1439,3028,1839,1692,1209,4500,4996,1097, 3565,3068,2911,4416, 579,3994,1291,2914,3728,1023, 868,3652,3458,1461,4763,3904,1822,4594, 900,1763, 1645,1933,4541, 517,2676,4744,1292,4498,3848,3508, 2425, 87,2627,2532,2375,3623,3112,932,1368, 501};
    const int MAX_LEN = sizeof(my_numbers)/sizeof(int);
    sort(my_numbers, MAX_LEN);
    printf("min: %d, max: %d\n", my_numbers[0], my_numbers[MAX_LEN-1]);
    int num = 3728;
    int pos = binary_search(my_numbers, MAX_LEN, num);
    printf("num: %d, position: %d\n", num, pos);
    num = 469;
    pos = binary_search(my_numbers, MAX_LEN, num);
    printf("num: %d, position: %d\n", num, pos);
    num = 20;
    pos = binary_search(my_numbers, MAX_LEN, num);
    printf("num: %d, position: %d\n", num, pos);
}

void sort(int*nums, const int len){
    for(int i = len-1, j, k; 0 < i; i --){
        for(int j = i - 1; 0 <= j; j --){
            if(nums[j] > nums[i]){
                k = nums[i];
                nums[i] = nums[j];
                nums[j] = k;
            }
        }
    }
}

int find_index(int* arr, const int s_pos, const int e_pos, const int find){
    int mid = ((e_pos+s_pos)/2);
    if(find == arr[mid]){
        return mid;
    } else if (find < arr[mid]){
        mid --;
        if(0 > mid) return -1;
        return find_index(arr, s_pos, mid, find);
    }
    mid ++;
    if(e_pos < mid) return -1;
    return find_index(arr, mid, e_pos, find);
}

int binary_search(int* arr, const int len, const int find){
    return find_index(arr, 0, len-1, find);
}
Download

Comments

Popular posts from this blog