Skip to content

Commit

Permalink
add code
Browse files Browse the repository at this point in the history
  • Loading branch information
greyireland committed Jun 14, 2020
1 parent 8a79009 commit 6dda558
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@
## 面试资源

另外面试还看了大概 100 本书,强烈推荐 🌝
分享一些计算机的经典书籍,大部分对面试应该都有帮助,强烈推荐 🌝

[我看过的 100 本书](https://github.com/greyireland/awesome-programming-books-1)

Expand Down
7 changes: 7 additions & 0 deletions src/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package main

import "fmt"

func main() {
fmt.Println("hello world")
}
47 changes: 47 additions & 0 deletions src/sort/heap_sort.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package sort

func HeapSort(a []int) []int {
// 1、无序数组a
// 2、将无序数组a构建为一个大根堆
for i := len(a)/2 - 1; i >= 0; i-- {
sink(a, i, len(a))
}
// 3、交换a[0]和a[len(a)-1]
// 4、然后把前面这段数组继续下沉保持堆结构,如此循环即可
for i := len(a) - 1; i >= 1; i-- {
// 从后往前填充值
swap(a, 0, i)
// 前面的长度也减一
sink(a, 0, i)
}
return a
}
func sink(a []int, i int, length int) {
for {
// 左节点索引(从0开始,所以左节点为i*2+1)
l := i*2 + 1
// 有节点索引
r := i*2 + 2
// idx保存根、左、右三者之间较大值的索引
idx := i
// 存在左节点,左节点值较大,则取左节点
if l < length && a[l] > a[idx] {
idx = l
}
// 存在有节点,且值较大,取右节点
if r < length && a[r] > a[idx] {
idx = r
}
// 如果根节点较大,则不用下沉
if idx == i {
break
}
// 如果根节点较小,则交换值,并继续下沉
swap(a, i, idx)
// 继续下沉idx节点
i = idx
}
}
func swap(a []int, i, j int) {
a[i], a[j] = a[j], a[i]
}
26 changes: 26 additions & 0 deletions src/sort/heap_sort_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package sort

import (
"reflect"
"testing"
)

func TestHeapSort(t *testing.T) {
type args struct {
a []int
}
tests := []struct {
name string
args args
want []int
}{
{"", args{a: []int{7, 8, 9, 2, 3, 5}}, []int{2, 3, 5, 7, 8, 9}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := HeapSort(tt.args.a); !reflect.DeepEqual(got, tt.want) {
t.Errorf("HeapSort() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit 6dda558

Please sign in to comment.