forked from huihut/interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
64 additions
and
9 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
// 二分查找(折半查找):对于已排序,若无序,需要先排序 | ||
|
||
// 非递归 | ||
int BinarySearch(vector<int> v, int value) | ||
{ | ||
if (v.size() <= 0) | ||
return -1; | ||
|
||
int low = 0; | ||
int high = v.size() - 1; | ||
while (low <= high) | ||
{ | ||
int mid = low + (high - low) / 2; | ||
if (v[mid] == value) | ||
return mid; | ||
else if (v[mid] > value) | ||
high = mid - 1; | ||
else | ||
low = mid + 1; | ||
} | ||
|
||
return -1; | ||
} | ||
|
||
// 递归 | ||
int BinarySearch2(vector<int> v, int value, int low, int high) | ||
{ | ||
if (low > high) | ||
return -1; | ||
int mid = low + (high - low) / 2; | ||
if (v[mid] == value) | ||
return mid; | ||
else if (v[mid] > value) | ||
return BinarySearch2(v, value, low, mid - 1); | ||
else | ||
return BinarySearch2(v, value, mid + 1, high); | ||
} |
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