码迷,mamicode.com
首页 > 编程语言 > 详细

golang 的排序sort

时间:2018-08-22 12:04:38      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:调用   Golan   less   quicksort   quick   port   lang   heap   epo   

首先看一下sort包的原理

func Sort(data Interface) {
    // Switch to heapsort if depth of 2*ceil(lg(n+1)) is reached.
    n := data.Len()
    maxDepth := 0
    for i := n; i > 0; i >>= 1 {
        maxDepth++
    }
    maxDepth *= 2
    quickSort(data, 0, n, maxDepth)
}

type Interface interface {
    // Len is the number of elements in the collection.
    Len() int
    // Less reports whether the element with
    // index i should sort before the element with index j.
    Less(i, j int) bool
    // Swap swaps the elements with indexes i and j.
    Swap(i, j int)
}
// 内部实现的四种排序算法
// 插入排序
func insertionSort(data Interface, a, b int)
// 堆排序
func heapSort(data Interface, a, b int)
// 快速排序
func quickSort(data Interface, a, b, maxDepth int)
// 归并排序
func symMerge(data Interface, a, m, b int)

 

再看个sort内部[]int的排序

 

// 首先定义了一个[]int类型的别名IntSlice 
type IntSlice []int
// 获取此 slice 的长度
func (p IntSlice) Len() int           { return len(p) }
// 比较两个元素大小 升序
func (p IntSlice) Less(i, j int) bool { return p[i] < p[j] }
// 交换数据
func (p IntSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
// sort.Ints()内部调用Sort() 方法实现排序
// 注意 要先将[]int 转换为 IntSlice类型 因为此类型才实现了Interface的三个方法 
func Ints(a []int) { Sort(IntSlice(a)) }

 

最后自己写一个例子

 

package main

import (
    "sort"
    "fmt"
)
type person struct {
    Name string
    Age int
}

type personSlice []person

func (s personSlice) Len() int { return len(s) }
func (s personSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s personSlice) Less(i, j int) bool { return s[i].Age < s[j].Age }  // 这里是关键,我比较了年龄这个字段

func main() {
    a := personSlice {
        {
            Name: "AAA",
            Age: 55,
        },
        {
            Name: "BBB",
            Age: 22,
        },
        {
            Name: "CCC",
            Age: 0,
        },
        {
            Name: "DDD",
            Age: 22,
        },
        {
            Name: "EEE",
            Age: 11,
        },
    }
    sort.Sort(a)
    fmt.Println(a)
}

 

ok!

golang 的排序sort

标签:调用   Golan   less   quicksort   quick   port   lang   heap   epo   

原文地址:https://www.cnblogs.com/huangliang-hb/p/9516611.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!