golang int64 排序_Golang: Slice关系排序

package main

import (

"fmt"

"log"

"strconv"

)

// Node ...type Node struct {

ID int64

Name string

PreID int64

NextID int64

IsTransferred bool

}

func genNodeList() []*Node {

var nodeList []*Node

for i := 0; i < 3; i++ {

nodeList = append(nodeList, &Node{

ID: int64(i + 1),

Name: "node_" + strconv.Itoa(i+1),

PreID: 0,

NextID: 0,

IsTransferred: false,

})

}

nodeList[0].NextID = 13

nodeList[0].IsTransferred = true

nodeList[1].PreID = 13

nodeList[1].NextID = 3

nodeList[2].PreID = 2

nodeList[2].NextID = 0

// Special node, it has relastions with node 0 and 1, it is in the middle // of both node 0 and 1 in relastions, but not in the storage order. nodeList = append(nodeList, &Node{

ID: 13,

Name: "node_13",

PreID: 1,

NextID: 2,

IsTransferred: false,

})

return nodeList

}

// Sort node list by relations. Here we use the node list generated by method// genNodeList, the list has 4 nodes, one of them is different and has id 13.// We assume we want to sort the list to put the node with ID 13 in the middle// of nodes with indice 0 and 1. Thus, we can straight the list.func sortNodeListByRelations(nodeList []*Node) []*Node {

newNodeList := new([]*Node)

var firstNode *Node

for _, v := range nodeList {

if v.PreID == 0 {

firstNode = v

}

}

*newNodeList = append(*newNodeList, firstNode)

findNextNode(firstNode, nodeList, newNodeList)

return *newNodeList

}

// The method find the next node of the node passed in the arguments, for test reason,// I don't tune the algorithm, I just blindly find the next node. If the method find the// next node of the current node, then it will append the next node into the newNodeList.// Here we should notice that the newNodeList is a pointer of a slice, otherwise, it won't// store the pointer we put into.func findNextNode(node *Node, nodeList []*Node, newNodeList *[]*Node) {

for _, v := range nodeList {

log.Println("I'm working on it.")

if node.NextID == v.ID {

log.Println("I find the next node.")

*newNodeList = append(*newNodeList, v)

if v.NextID != 0 {

findNextNode(v, nodeList, newNodeList)

}

}

}

}

func main() {

nodeList := genNodeList()

sortedNodeList := sortNodeListByRelations(nodeList)

for _, v := range sortedNodeList {

fmt.Println("node_id => ", v.ID, "node_name => ", v.Name, " pre_id => ", v.PreID,

" next_id => ", v.NextID, " is_transferred => ", v.IsTransferred)

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值