二分法查找数组元素

二分法实现查找有前提条件:待查找数组元素必须为有序排列的;

二分法查找具有局限性:一次只能找一个数;

1.在整数数组查找

#include 






/*实现二分法查找一个整数元素*/
int divide_search(int* arr, int length, int value);
int main() {
    int arr[] = { 10,11,12,21,23,31,33,37,55,60,61,70 };
    int length = sizeof(arr) / sizeof(int);
    int rank = 0, value = 0;

    printf("请输入需要查找的数据\n");
    scanf_s("%d", &value);
    rank = divide_search(arr, length, value);
    printf("rank=%d", rank);

    return 0;
}

int divide_search(int* arr, int length, int value) {
    int left = 0, right = length - 1,mid=0;
    while (left <= right) {
        int mid=(left+right)>>1;//用于取平均值,运算速度更快
        if (value < arr[mid]) {
            right = mid - 1;
        }
        else if (value > arr[mid]) {
            left = mid + 1;
        } 
        else {
            printf("value=%d\n", arr[mid]); 
            return mid;                
        }
    }
    if(left>right){
        printf("未找到"); return -1;
    }
}

2.在浮点数数组查找

#include 






/*实现二分法查找一个小数*/
int divide_search(float* arr, int length, float value);
int main() 
{
    float arr[] = { 10.0,11.1,12.3,21.5,23.1,31.2,33.3,37.5,55.5,60.1,61.0,70.1 };
    int length = sizeof(arr) / sizeof(int);
    int rank = 0; 
    float value = 0;
    printf("请输入需要查找的数据\n"); scanf_s("%f", &value);
    rank = divide_search(arr, length, value);
    printf("rank=%d", rank);

    return 0;
}
int divide_search(float* arr, int length, float value) 
{
    int left = 0, right = length - 1;int mid = 0;           
    while (left <= right) {
        int mid=(left+right)>>1; 
        if (value < arr[mid]) {
            right = mid - 1;
        }
        else if (value > arr[mid]) {
            left = mid + 1;
        } 
        else {
            printf("value=%f\n", arr[mid]); return mid;                
        }
    }
    if(left>right){
        printf("未找到"); 
        return -1;
    }
}

你可能感兴趣的:(算法,数据结构,c语言,排序算法)