Skip to content

Instantly share code, notes, and snippets.

@Cartman0
Created June 24, 2015 04:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cartman0/50af4620acd626b5737b to your computer and use it in GitHub Desktop.
Save Cartman0/50af4620acd626b5737b to your computer and use it in GitHub Desktop.
BinarySearch(C++)
#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