12 Star 94 Fork 23

RACHEL/fastsearch

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
sort.go 1.46 KB
一键复制 编辑 原始数据 按行查看 历史
内容可能含有违规信息 提交于 2024-09-04 17:12 +08:00 . 优化索引效率
package sorts
import (
"log"
"sync"
"gitee.com/rachel_os/fastsearch/utils"
"github.com/emirpasic/gods/trees/avltree"
)
// IdSort 二叉树对id 进行打分和排序
type IdSort struct {
Tree *avltree.Tree
sync.Mutex
}
func NewIdSortTree() *IdSort {
return &IdSort{
Tree: &avltree.Tree{Comparator: utils.Uint32Comparator},
}
}
func (e *IdSort) Add(key uint32) {
count, found := e.Tree.Get(key)
val := 1
if found {
val = count.(int) + 1
}
e.Lock()
defer e.Unlock()
e.Tree.Put(key, val)
}
func (e *IdSort) Size() int {
return e.Tree.Size()
}
// GetAll 正序获取
func (e *IdSort) GetAll(order string) []uint32 {
scores := make([]int, 0)
ids := make([]uint32, 0)
it := e.Tree.Iterator()
_tt := utils.ExecTime(func() {
for it.Next() {
scores = append(scores, it.Value().(int))
ids = append(ids, it.Key().(uint32))
}
})
log.Println("迭代耗时:", _tt)
_t := utils.ExecTime(func() {
//ids 降序
if order == "desc" {
for i, j := 0, len(ids)-1; i < j; i, j = i+1, j-1 {
ids[i], ids[j] = ids[j], ids[i]
scores[i], scores[j] = scores[j], scores[i]
}
}
})
log.Println("id排序耗时:", _t)
_t = utils.ExecTime(func() {
// 排序,得分越高 排越前
for i := 0; i < len(scores); i++ {
for j := i + 1; j < len(scores); j++ {
if scores[i] < scores[j] {
scores[i], scores[j] = scores[j], scores[i]
ids[i], ids[j] = ids[j], ids[i]
}
}
}
})
log.Println("得分排序耗时:", _t)
return ids
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/rachel_os/fastsearch.git
git@gitee.com:rachel_os/fastsearch.git
rachel_os
fastsearch
fastsearch
98a29f8d6bf9

搜索帮助