2022-12-05 20:39:42 +08:00
|
|
|
// File: binary_search_test.go
|
2022-12-05 22:32:56 +08:00
|
|
|
// Created Time: 2022-12-05
|
2022-12-05 20:39:42 +08:00
|
|
|
// Author: Slone123c (274325721@qq.com)
|
|
|
|
|
2023-05-21 19:26:52 +08:00
|
|
|
package chapter_searching
|
2022-12-05 20:39:42 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"testing"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestBinarySearch(t *testing.T) {
|
|
|
|
var (
|
2023-05-21 19:26:52 +08:00
|
|
|
target = 6
|
2023-05-21 19:29:24 +08:00
|
|
|
nums = []int{1, 3, 6, 8, 12, 15, 23, 26, 31, 35}
|
2022-12-05 20:39:42 +08:00
|
|
|
expected = 2
|
|
|
|
)
|
|
|
|
// 在数组中执行二分查找
|
|
|
|
actual := binarySearch(nums, target)
|
2023-05-21 19:26:52 +08:00
|
|
|
fmt.Println("目标元素 6 的索引 =", actual)
|
2022-12-05 20:39:42 +08:00
|
|
|
if actual != expected {
|
2023-05-21 19:26:52 +08:00
|
|
|
t.Errorf("目标元素 6 的索引 = %d, 应该为 %d", actual, expected)
|
2022-12-05 20:39:42 +08:00
|
|
|
}
|
|
|
|
}
|
2023-05-29 12:23:52 +08:00
|
|
|
|
|
|
|
func TestBinarySearchEdge(t *testing.T) {
|
|
|
|
target := 6
|
|
|
|
nums := []int{1, 3, 6, 6, 6, 6, 6, 10, 12, 15}
|
|
|
|
// 二分查找最左一个元素
|
|
|
|
indexLeft := binarySearchLeftEdge(nums, target)
|
|
|
|
fmt.Println("数组中最左一个元素 6 的索引 = ", indexLeft)
|
|
|
|
|
|
|
|
// 二分查找最右一个元素
|
|
|
|
indexRight := binarySearchRightEdge(nums, target)
|
|
|
|
fmt.Println("数组中最右一个元素 6 的索引 = ", indexRight)
|
|
|
|
}
|