Skip to content

Instantly share code, notes, and snippets.

@congjf
Last active January 3, 2016 07:49
Show Gist options
  • Save congjf/8431917 to your computer and use it in GitHub Desktop.
Save congjf/8431917 to your computer and use it in GitHub Desktop.
Algorithms using Golang
Algorithms using Golang
// Sort
type Sort struct {
Name string
CompareTimes int
ExchangeTimes int
TotalTimes int
}
// 选择排序
func (s *Sort) Selecton(array []int) []int {
s.Name = "Selecton"
for j := 0; j < len(array); j++ {
for i := len(array) - 1; i > j; i-- {
s.CompareTimes++
if less(array[i], array[i-1]) {
ex := array[i-1]
array[i-1] = array[i]
array[i] = ex
s.ExchangeTimes += 3
}
}
}
s.TotalTimes = s.CompareTimes + s.ExchangeTimes
return array
}
// 插入排序
func (s *Sort) Insert(array []int) []int {
s.Name = "Insert"
for j := 0; j < len(array)-1; j++ {
for i := j; i >= 0; i-- {
s.CompareTimes++
if less(array[i+1], array[i]) {
ex := array[i+1]
array[i+1] = array[i]
array[i] = ex
s.ExchangeTimes += 3
} else {
break
}
}
}
s.TotalTimes = s.CompareTimes + s.ExchangeTimes
return array
}
// 希尔排序
func (s *Sort) Hill(array []int) []int {
s.Name = "Hill"
N := len(array)
h := 1
for h < N/3 {
h = 3*h + 1
}
for h >= 1 {
for i := h; i < N; i++ {
for j := i; j >= h; j -= h {
s.CompareTimes++
if less(array[j], array[j-h]) {
ex := array[j]
array[j] = array[j-h]
array[j-h] = ex
s.ExchangeTimes += 3
}
}
}
h = h / 3
}
s.TotalTimes = s.CompareTimes + s.ExchangeTimes
return array
}
func less(a int, b int) bool {
return a < b
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment