C binary search recursive and non recursive implementation code

  • 2020-04-01 21:36:46
  • OfStack


#include <stdio.h>
int binSearch(int arr[], int low, int high, int key);
int binSearch2(int arr[], int low, int high, int key);
int binSearch3(int arr[],int start,int ends,int key);
int main() {
    int arr[]={3,8,11,15,17,22,23,26,28,29,34};
    //printf("%d",binSearch(arr,0,10,26));
    printf("%d",binSearch3(arr,0,10,26));
    return 1;
}
int binSearch(int arr[], int low, int high, int key) {
    int flag=-1;
    int mid = (low + high) / 2;
    if (low > high) {
        flag= -1;
    } else {
        if (arr[mid] < key) {
            flag= binSearch(arr, mid + 1, high, key);
        } else if (arr[mid]>key) {
            //For example, the node you're looking for is at the bottom layer & NBSP;   Then this layer will return to the subscript and catch it with a flag...
            flag= binSearch(arr,low,mid-1,key);//I almost forgot to flag the catch return value again
        } else {
            flag= mid;
        }
    }
    return flag;
}

//ok==============================
int binSearch2(int arr[], int low, int high, int key) {
    int mid = (low + high) / 2;
    if (low > high) {
        return -1;
    } else {
        if (arr[mid] < key) {
            return binSearch2(arr, mid + 1, high, key);
        } else if (arr[mid]>key) {
            return binSearch2(arr,low,mid-1,key);
        } else {
            return mid;
        }
    }
}
int binSearch3(int arr[],int start,int ends,int key){
    int mid=-1;
    while(start<=ends){
        mid=(start+ends)/2;
        if(arr[mid]<key){
            start=mid+1;
        }else if(arr[mid]>key){
            ends=mid-1;
        }else{
            break;
        }
    }//The end of the above loop is not necessarily start> Ends of   Because of the break statement
    if(start>ends){
        mid=-1;
    }
    return mid;
}        


Related articles: