mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2024-12-27 12:56:17 +00:00
add 二分查找详解code in Go
This commit is contained in:
parent
b46603ce37
commit
a177043d3f
@ -118,6 +118,8 @@ target < nums[mid] 则在左半区间继续进行搜索,即 right = mid -1;
|
||||
|
||||
下面我们来看一下二分查找的代码,可以认真思考一下 if 语句的条件,每个都没有简写。
|
||||
|
||||
Java Code:
|
||||
|
||||
```java
|
||||
public static int binarySearch(int[] nums,int target,int left, int right) {
|
||||
//这里需要注意,循环条件
|
||||
@ -139,6 +141,31 @@ target < nums[mid] 则在左半区间继续进行搜索,即 right = mid -1;
|
||||
}
|
||||
```
|
||||
|
||||
Go Code:
|
||||
|
||||
```go
|
||||
func binarySearch(nums []int, target, left, right int) int {
|
||||
//这里需要注意,循环条件
|
||||
for left <= right {
|
||||
//这里需要注意,计算mid
|
||||
mid := left + ((right - left) >> 1)
|
||||
if nums[mid] == target {
|
||||
return mid
|
||||
} else if nums[mid] < target {
|
||||
//这里需要注意,移动左指针
|
||||
left = mid + 1
|
||||
} else if nums[mid] > target {
|
||||
//这里需要注意,移动右指针
|
||||
right = mid - 1
|
||||
}
|
||||
}
|
||||
//没有找到该元素,返回 -1
|
||||
return -1
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
二分查找的思路及代码已经理解了,那么我们来看一下实现时容易出错的地方
|
||||
@ -155,6 +182,8 @@ target < nums[mid] 则在左半区间继续进行搜索,即 right = mid -1;
|
||||
|
||||
下面我们来看一下二分查找的递归写法
|
||||
|
||||
Java Code:
|
||||
|
||||
```java
|
||||
public static int binarySearch(int[] nums,int target,int left, int right) {
|
||||
|
||||
@ -176,5 +205,28 @@ public static int binarySearch(int[] nums,int target,int left, int right) {
|
||||
}
|
||||
```
|
||||
|
||||
Go Code:
|
||||
|
||||
```go
|
||||
func binarySearch(nums []int, target, left, right int) int {
|
||||
|
||||
if left <= right {
|
||||
mid := left + ((right - left) >> 1)
|
||||
if nums[mid] == target {
|
||||
//查找成功
|
||||
return mid
|
||||
} else if nums[mid] > target {
|
||||
//新的区间,左半区间
|
||||
return binarySearch(nums, target, left, mid-1)
|
||||
} else if nums[mid] < target {
|
||||
//新的区间,右半区间
|
||||
return binarySearch(nums, target, mid+1, right)
|
||||
}
|
||||
}
|
||||
//不存在返回-1
|
||||
return -1
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user