Created
June 24, 2015 04:48
-
-
Save Cartman0/50af4620acd626b5737b to your computer and use it in GitHub Desktop.
BinarySearch(C++)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <algorithm> | |
//二分探索 | |
bool mybinary_search( const int a[], const unsigned int start_idx, const unsigned int end_idx, const int target, int& idx){ | |
unsigned int start = start_idx; | |
unsigned int end = end_idx; | |
while((end - start) >= 0){ | |
int mid = (end + start) / 2; | |
if(a[mid] == target){ | |
idx = mid; | |
return true; | |
}else if(a[mid] > target){ | |
end = mid - 1; | |
}else { | |
start = mid + 1; | |
} | |
} | |
return false; | |
} | |
int main() { | |
int N = 10; | |
int A[N] = {20, 10, 30, 40, 50, 60, 80, 90, 70, 100}; | |
std::sort(A, A+N); | |
int target = 100; | |
int idx = -1; | |
if(mybinary_search(A, 0, N - 1, target, idx)){ | |
std::cout << "Success:" << idx << std::endl; | |
} | |
//std::binary_search Test | |
if (std::binary_search(A, A+N, 75)) { | |
std::cout << "Success" << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment