Skip to content

Commit

Permalink
Merge pull request astaxie#204 from fugr/master
Browse files Browse the repository at this point in the history
sort update
  • Loading branch information
astaxie committed Aug 22, 2014
2 parents 22b5d5c + 9ee4deb commit 9e905a1
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 27 deletions.
28 changes: 1 addition & 27 deletions sort/Interface.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,30 +85,4 @@
// liver (1494g)
// pancreas (131g)
}


代码案例(二):

package main

import (
"fmt"
"sort"
)

type Reverse struct {
sort.Interface
}

// Less returns the opposite of the embedded implementation's Less method.

func (r Reverse) Less(i, j int) bool {
return r.Interface.Less(j, i)
}

func main() {
s := []int{5, 2, 6, 3, 1, 4} // unsorted
sort.Sort(Reverse{sort.IntSlice(s)})
fmt.Println(s) // [6 5 4 3 2 1]
}


4 changes: 4 additions & 0 deletions sort/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,17 @@

- [Sort(data Interface)](Sort.md)

- [Stable(data Interface)](Stable.md)

- [Strings(a []string)](Strings.md)

- [StringsAreSorted(a []string) bool](StringsAreSorted.md)

# 结构

- [type Interface](Interface.md)

- [Reverse(data Interface) Interface](Reverse.md)

- [type Float64Slice](Float64Slice.md)
- Len() int
Expand Down
31 changes: 31 additions & 0 deletions sort/Reverse.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
## func Reverse(data Interface) Interface

参数列表

- data 表示要逆序的 Interface 数据

返回值:

- 返回 Interface

功能说明:

- Reverse 返回逆序的Inferface数据

代码案例:

package main

import (
"fmt"
"sort"
)

func main() {
s := []int{5, 2, 6, 3, 1, 4} // unsorted
sort.Sort(sort.Reverse(sort.IntSlice(s)))
fmt.Println(s) // [6 5 4 3 2 1]
}



41 changes: 41 additions & 0 deletions sort/Stable.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
## func Stable(data Interface)

参数列表

- data 表示要判断的 Interface 数据

功能说明:

Stable 稳定排序算法,算法会将相等的元素值维持其相对次序。如果一个排序算法是稳定的,当有两个有相等的元素值 R 和 S,且在原本的列表中 R 出现在 S 之前,那么在排序过的列表中 R 也将会是在 S 之前。对于比较排序算法,我们都能给出 n 个输入的数值,使算法以 Ω(n*logn) 时间运行。稳定排序算法:插入排序、冒泡排序、归并排序、计数排序、基数排序、桶排序。

代码案例:

package main

import (
"fmt"
"sort"
)

type MyString []string

func (s MyString) Len() int {
return len(s)
}
func (s MyString) Less(i, j int) bool {
if s[i] == "" {
return true
}
if s[j] == "" {
return false
}
return []byte(s[i])[0] < []byte(s[j])[0] //比较字符串的第一个字符大小
}
func (s MyString) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func main() {
data := MyString{"5A*", "24", "65", "23", "1", "57", "4", "624"} // unsorted
sort.Stable(data)
fmt.Println(data) // [1 24 23 4 5A* 57 65 624]
}

0 comments on commit 9e905a1

Please sign in to comment.