add 二分查找详解code in Go

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

View File

@ -118,27 +118,54 @@ target < nums[mid] 则在左半区间继续进行搜索,即 right = mid -1
下面我们来看一下二分查找的代码可以认真思考一下 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
}
```