首页 > 代码库 > [算法]各种二叉搜索

[算法]各种二叉搜索

1,给定一个有序数组values,求任意一个i使得values[i]等于v,不存在返回-1

int search(int* values,int len,int key){    if(!values || len <=0) return -1;    int low=0;    int high=len-1;    while(low<=high)    {        int mid =(low+high)/2;        if(values[mid]==key) return mid;        else if(values[mid]>key) high=mid-1;        else low = mid +1;    }    return -1;}

 

2,给定一个有序数组values,求最小的i使得values[i]等于v,不存在返回-1

int searchFirst(int * values,int len,int key){    if(!values || len <=0) return -1;    int low=0;    int high=len-1;    while(low<=high)    {        int mid =(low+high)/2;        if(values[mid]==key)        {            if(mid==0) return mid;            else if(values[mid-1]<key) return mid;            else high=mid-1;        }        else if (values[mid]>key) high=mid-1;        else low=mid+1;    }    return -1;}

 

3,给定一个有序数组values,求最大的i使得values[i]等于v,不存在返回-1

int searchLast(int* values,int len,int key){    if(!values || len <=0) return -1;        int low=0;        int high=len-1;        while(low<=high)        {            int mid =(low+high)/2;            if(values[mid]==key)            {                if(mid==len-1) return mid;                else if(values[mid+1]>key) return mid;                else low=mid+1;            }            else if (values[mid]>key) high=mid-1;            else low=mid+1;        }    return -1;}

 

4,给定一个有序数组values,求最大的i使得values[i]小于v,不存在返回-1

int searchLargestSmallThan(int* values,int len,int key){    if(!values || len <=0) return -1;    int low=0,high=len-1;    while(low <= high){        int mid = (low+high)/2;        if(values[mid]>=key) high=mid-1;        else{            if(mid<len-1 && values[mid+1]>=key) return mid;            else                low=mid+1;        }    }    return -1;}

 

4,给定一个有序数组values,求最小的i使得values[i]大于v,不存在返回-1

int searchSmallestLargeThan(int* values, int len,int key){    if(!values || len <=0) return -1;    int low=0,high=len-1;    while(low <= high){        int mid = (low+high)/2;        if(values[mid]<=key) low=mid+1;        else{            if(mid>0 && values[mid-1]<=key) return mid;            else                high=mid-1;        }    }    return -1;}

 

[算法]各种二叉搜索