5.3. 数据结构-二分搜索

213 阅读2分钟

涉及知识点

  1. 二分查找的前提是数组有序
  2. 有重复元素时:
    1. 返回第一个匹配的位置
    2. 返回最后一个匹配的位置
    3. 找到任意一个匹配的位置返回
  3. go test测试
  4. 随机数 r := rand.New(rand.NewSource(time.Now().UnixNano()))
  5. 利用sort.SerachInts()查找最后一个匹配的元素

1. search.go

package ch5

import "fmt"

//能查到,有多个重复元素时无法返回第一个出现的位置
func linearSearchBackFirst(s []int, val int) int {
	for i, v := range s {
		if v == val {
			return i
		}
	}
	return -1
}

//能查到,有多个重复元素时无法返回最后一个出现的位置
func linearSearchBackLast(s []int, val int) int {
	for i := len(s) - 1; i >= 0; i-- {
		if s[i] == val {
			return i
		}
	}
	return -1
}

//能查到,但有多个重复元素时无法返回第一个出现的位置
func binarySearch(s []int, val int) int {
	for left, mid, right := 0, 0, len(s); left < right; {
		mid = (left + right) >> 1
		if s[mid] == val {
			return mid
		}
		if val > s[mid] {
			left = mid + 1
		} else if val < s[mid] {
			right = mid
		}
	}
	return -1
}

//能查到,但有多个重复元素时返回第一个出现的位置
func binarySearchBackFirst(s []int, val int) int {
	left, mid, right := 0, 0, len(s)-1
	for left < right {
		mid = (left + right) >> 1
		if val > s[mid] {
			left = mid + 1
		} else {
			right = mid
		}
	}
	if s[left] == val {
		return left
	} else {
		return -1
	}
}

//能查到,但有多个重复元素时返回最后一个出现的位置
func binarySearchBackLast(s []int, val int) int {
	left, mid, right := 0, 0, len(s)-1
	for left < right {
		mid = (left + right + 1) / 2 //保证取到中间靠后的位置

		if s[mid] > val {
			right = mid - 1
		} else {
			left = mid
		}
	}
	fmt.Println("s[right]", s[right], right)
	fmt.Println("val", val)
	if s[right] == val {
		return right
	} else {
		return -1
	}
}

1. search_test.go

package ch5

import (
	"fmt"
	"math/rand"
	"sort"
	"testing"
	"time"
)

func Test_search(t *testing.T) {
	s := make([]int, 1000)
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < len(s); i++ {
		s[i] = r.Int() % 1000
	}

	sort.Ints(s)
	fmt.Println(s)
	for _, v := range s {
		if linearSearchBackFirst(s, v) != binarySearchBackFirst(s, v) {
			fmt.Println("linearSearchBackFirst(s, v) ", v, linearSearchBackFirst(s, v))
			fmt.Println("binarySearchBackFirst(s, v) ", v, binarySearchBackFirst(s, v))
		}
		if linearSearchBackLast(s, v) != binarySearchBackLast(s, v) {
			fmt.Println("linearSearchBackLast(s, v) ", v, linearSearchBackLast(s, v))
			fmt.Println("binarySearchBackLast(s, v) ", v, binarySearchBackLast(s, v))
		}
	}

}

sort库里面的sort实现

利用sort函数的SearchInts ?

  1. 返回第一个匹配的位置 sort.SearchInts(s,key)
  2. 返回最后一个匹配的位置
idx:=sort.SearchInts(s,key+1)
if s[idx] == key {
    return idx
} else {
    return -1;
}
// SearchInts searches for x in a sorted slice of ints and returns the index
// as specified by Search. The return value is the index to insert x if x is
// not present (it could be len(a)).
// The slice must be sorted in ascending order.
//
func SearchInts(a []int, x int) int {
	return Search(len(a), func(i int) bool { return a[i] >= x })
}
// Search uses binary search to find and return the smallest index i
// in [0, n) at which f(i) is true, assuming that on the range [0, n),
// f(i) == true implies f(i+1) == true. That is, Search requires that
// f is false for some (possibly empty) prefix of the input range [0, n)
// and then true for the (possibly empty) remainder; Search returns
// the first true index. If there is no such index, Search returns n.
// (Note that the "not found" return value is not -1 as in, for instance,
// strings.Index.)
// Search calls f(i) only for i in the range [0, n).
//
// A common use of Search is to find the index i for a value x in
// a sorted, indexable data structure such as an array or slice.
// In this case, the argument f, typically a closure, captures the value
// to be searched for, and how the data structure is indexed and
// ordered.
//
// For instance, given a slice data sorted in ascending order,
// the call Search(len(data), func(i int) bool { return data[i] >= 23 })
// returns the smallest index i such that data[i] >= 23. If the caller
// wants to find whether 23 is in the slice, it must test data[i] == 23
// separately.
//
// Searching data sorted in descending order would use the <=
// operator instead of the >= operator.
//
// To complete the example above, the following code tries to find the value
// x in an integer slice data sorted in ascending order:
//
//	x := 23
//	i := sort.Search(len(data), func(i int) bool { return data[i] >= x })
//	if i < len(data) && data[i] == x {
//		// x is present at data[i]
//	} else {
//		// x is not present in data,
//		// but i is the index where it would be inserted.
//	}
//
// As a more whimsical example, this program guesses your number:
//
//	func GuessingGame() {
//		var s string
//		fmt.Printf("Pick an integer from 0 to 100.\n")
//		answer := sort.Search(100, func(i int) bool {
//			fmt.Printf("Is your number <= %d? ", i)
//			fmt.Scanf("%s", &s)
//			return s != "" && s[0] == 'y'
//		})
//		fmt.Printf("Your number is %d.\n", answer)
//	}
//
func Search(n int, f func(int) bool) int {
	// Define f(-1) == false and f(n) == true.
	// Invariant: f(i-1) == false, f(j) == true.
	i, j := 0, n
	for i < j {
		h := int(uint(i+j) >> 1) // avoid overflow when computing h
		// i ≤ h < j
		if !f(h) {
			i = h + 1 // preserves f(i-1) == false
		} else {
			j = h // preserves f(j) == true
		}
	}
	// i == j, f(i-1) == false, and f(j) (= f(i)) == true  =>  answer is i.
	return i
}