C Binary Search implementation code for recursion and non-recursion

Source: Internet
Author: User

Copy codeThe Code is 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 [] = {, 22, 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, if the node to be searched is located in the lower layer, the subscript will be returned for this layer and the flag will be used to catch it...
Flag = binSearch (arr, low, mid-1, key); // I almost forgot to use 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;
}
} // After the above loop ends, it is not necessarily start> ends because of the break statement.
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.