diff --git a/Algorithm/BinarySearch.h b/Algorithm/BinarySearch.h index 38ec320..2387a7d 100644 --- a/Algorithm/BinarySearch.h +++ b/Algorithm/BinarySearch.h @@ -1,22 +1,22 @@ // 二分查找(折半查找):对于已排序,若无序,需要先排序 // 非递归 -int BinarySearch(vector v, int value) -{ - if (v.size() <= 0) - return -1; - int low = 0; - int high = v.size() - 1; - while (low <= high) - { +int BinarySearch(vector v, int value , int low, int high) { + if (v.size() <= 0) { + return -1; + } + while (low <= high) { int mid = low + (high - low) / 2; - if (v[mid] == value) + if (v[mid] == value) { return mid; - else if (v[mid] > value) + } + else if (v[mid] > value) { high = mid - 1; - else + } + else { low = mid + 1; + } } return -1; @@ -34,4 +34,4 @@ int BinarySearch2(vector v, int value, int low, int high) return BinarySearch2(v, value, low, mid - 1); else return BinarySearch2(v, value, mid + 1, high); -} \ No newline at end of file +}