feat(Go-Tool):新增Horspool字符串查找算法及其单测、新增计数排序及其单测

This commit is contained in:
huangzj
2020-08-26 12:01:20 +08:00
parent f4f18b3866
commit ddee50e1cb
4 changed files with 169 additions and 0 deletions
+47
View File
@@ -0,0 +1,47 @@
/*
* @Author : huangzj
* @Time : 2020/8/21 9:28
* @Description:计数排序,时间复杂度:Ο (n+k)、空间复杂度是 O(k)
* 限制:1.当数列最大最小值差距过大时,并不适用计数排序。2.当数列元素不是整数,并不适用计数排序。
* 参考地址:https://blog.csdn.net/csdnnews/article/details/83005778
*/
package sort
import "math"
func CountingSort(list []int) []int {
min, max := findMinAndMax(list)
countArray := make([]int, max-min+1)
for index := range list {
countArray[list[index]-min]++ //根据偏移量对数组某个下标的元素进行增一,如果这个位置元素存在
}
//创建结果数组,这边其实可以直接输出或者使用原来的数组
result := make([]int, len(list))
pos := 0
for index := range countArray {
for countArray[index] != 0 {
result[pos] = index + min
pos++
countArray[index]--
}
}
return result
}
func findMinAndMax(list []int) (int, int) {
min := math.MaxInt64
max := math.MinInt64
//找到数组中的最大值和最小值
for _, num := range list {
if num > max {
max = num
}
if num < min {
min = num
}
}
return min, max
}
+43
View File
@@ -0,0 +1,43 @@
/*
* @Author : huangzj
* @Time : 2020/8/21 9:28
* @Description
*/
package sort
import (
"fmt"
"testing"
)
func TestCountingSort(t *testing.T) {
list1 := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
CountingSort(list1)
for _, r := range list1 {
fmt.Print(r, " ")
}
fmt.Println()
list2 := []int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}
result2 := CountingSort(list2)
for _, r := range result2 {
fmt.Print(r, " ")
}
fmt.Println()
list3 := []int{1, 432, 12, 67, 341, 874, 56332, 43, 6564, 234, 980, 4234, 6589932, 80, 42, 4234, 55}
result3 := CountingSort(list3)
for _, r := range result3 {
fmt.Print(r, " ")
}
fmt.Println()
list4 := []int{4523325, 21, 43, 1, 265, 7657, 8754, 234, 543, 536, 2, 6543, 772, 432, 5, 6, 7214, 6754}
result4 := CountingSort(list4)
for _, r := range result4 {
fmt.Print(r, " ")
}
fmt.Println()
}