add 二分查找详解code in Go

This commit is contained in:
lincongcong 2021-07-19 14:33:01 +08:00
parent b46603ce37
commit a177043d3f

View File

@ -116,29 +116,56 @@ target < nums[mid] 则在左半区间继续进行搜索,即 right = mid -1
![二分查找2](https://img-blog.csdnimg.cn/img_convert/eb648f86b4ada5b32afc7a52e78d9953.gif)
下面我们来看一下二分查找的代码可以认真思考一下 if 语句的条件每个都没有简写
下面我们来看一下二分查找的代码可以认真思考一下 if 语句的条件每个都没有简写
Java Code:
```java
public static int binarySearch(int[] nums,int target,int left, int right) {
//这里需要注意循环条件
while (left <= right) {
//这里需要注意计算mid
int 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;
}
public static int binarySearch(int[] nums,int target,int left, int right) {
//这里需要注意循环条件
while (left <= right) {
//这里需要注意计算mid
int 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;
}
//没有找到该元素返回 -1
return -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,25 +182,50 @@ target < nums[mid] 则在左半区间继续进行搜索,即 right = mid -1
下面我们来看一下二分查找的递归写法
Java Code:
```java
public static int binarySearch(int[] nums,int target,int left, int right) {
if (left <= right) {
int 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);
}
if (left <= right) {
int 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;
}
//不存在返回-1
return -1;
}
```
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
}
```