二分查找 O l o g n Ologn Ologn
针对的是一个有序的数据集合(这点很重要),查找思想有点类似分治思想。每次都通过跟区间的中间元素对比,将待查找的区间缩小为之前的一半,直到找到要查找的元素,或者区间被缩小为 0。
二分查找针对的必须是已经排序过的有序数组,否则不能使用该算法
PHP
function search($nums, $target)
{
sort($nums);
$start = 0;
$end = count($nums) - 1;
return binary_search($nums, $target, $start, $end);
}
function binary_search($nums, $target, $start, $end)
{
if ($start > $end) {
return false;
}
$middle = floor(($start + $end) / 2);
if ($nums[$middle] == $target) {
return $target;
} elseif ($nums[$middle] > $target) {
return binary_search($nums, $target, $start, $middle - 1);
} else {
return binary_search($nums, $target, $middle + 1, $end);
}
}
//查找多个相同结果中的第一个
function binary_search_first($nums, $target, $start, $end)
{
if ($start > $end) {
return false;
}
$middle = floor(($start + $end) / 2);
if ($nums[$middle] == $target) {
if ($middle == 0 || $nums[$middle - 1] != $target) {
return $target;
} else {
return binary_search($nums, $target, $start, $middle - 1);
}
} elseif ($nums[$middle] > $target) {
return binary_search($nums, $target, $start, $middle - 1);
} else {
return binary_search($nums, $target, $middle + 1, $end);
}
}
//查找多个相同结果中的最后一个
function binary_search_last($nums, $target, $start, $end)
{
if ($start > $end) {
return false;
}
$middle = floor(($start + $end) / 2);
if ($nums[$middle] == $target) {
if ($middle == count($nums) - 1 || $nums[$middle + 1] != $target) {
return $target;
} else {
return binary_search($nums, $target, $middle + 1, $end);
}
} elseif ($nums[$middle] > $target) {
return binary_search($nums, $target, $start, $middle - 1);
} else {
return binary_search($nums, $target, $middle + 1, $end);
}
}
GO
package main
import (
"fmt"
"sort"
"errors"
"math"
)
func main() {
nums := []int{4, 5, 6, 3, 2, 1}
re, err := search(&nums, 6)
if (err != nil) {
fmt.Println(err)
} else {
fmt.Println(re)
}
}
func search(nums *[]int, target int) (int, error) {
sort.Ints(*nums)
return binarySearch(nums, target, 0, len(*nums) - 1)
}
func binarySearch(nums *[]int, target int, start int, end int) (int, error) {
if start > end {
return 0, errors.New("no found")
}
middle := int(math.Floor(float64((start + end) / 2)))
if (*nums)[middle] == target {
return target, nil
}
if target >= (*nums)[middle] {
return binarySearch(nums, target, middle + 1, end)
} else {
return binarySearch(nums, target, start + 1, middle)
}
}