C Two-point lookup recursive and non-recursive implementation code _c language

Source: Internet
Author: User

Copy Code code as follows:

#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, to find the node at the bottom of this layer then this layer will return to the subscript to catch with flag ...
flag= Binsearch (Arr,low,mid-1,key)//And almost forgot to use the flag to catch the return value

} 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 above loops are not necessarily start>ends because there are break statements
if (start>ends) {
Mid=-1;
}
return mid;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.