• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

数据结构 二分查找 递归与非递归算法

开发技术 开发技术 6天前 16次浏览
#include <stdlib.h>
#include <stdio.h>
//二分查找非递归

int Binary_Search(int list[],int key,int length){
    int low=0,high=length-1;
    while (low<=high){
        int mid=(high+low)/2;
        if (list[mid]==key)
            return ++mid;
        else if (list[mid]>key)
            high=mid-1;
        else if (list[mid]<key)
            low=mid+1;
    }
    return -1;
}
int main(){
    int list[10]={1,3,5,6,7,8,9,10,11,19};
    int number=Binary_Search(list,10,10);
    printf("%d",number);
    return 0;
}
#include <stdlib.h>
#include <stdio.h>
//二分查找 递归

int Binary_Search(int list[],int key,int low,int high){
    int mid = (low+high)/2;
        if (list[mid]==key)
            return ++mid;
        else if (list[mid]<key)
            Binary_Search(list,key,mid+1,high);
        else if (list[mid]>key)
            Binary_Search(list,key,low,high-1);
}
int main(){
    int list[10]={1,3,5,6,7,8,9,10,11,19};
    int result=Binary_Search(list,10,0,10);
    printf("%d",result);
    return 0;
}

喜欢 (0)