Skip to content

Commit

Permalink
12_sort
Browse files Browse the repository at this point in the history
  • Loading branch information
leotyliu(刘天一) committed Oct 17, 2018
1 parent f4d5187 commit 58e8ec4
Show file tree
Hide file tree
Showing 4 changed files with 108 additions and 0 deletions.
47 changes: 47 additions & 0 deletions go/12_sorts/MergeSort.go
Original file line number Diff line number Diff line change
@@ -1 +1,48 @@
package _2_sorts

func MergeSort(arr []int) {
arrLen := len(arr)
if arrLen <= 1 {
return
}

mergeSort(arr, 0, arrLen-1)
}

func mergeSort(arr []int, start, end int) {
if start >= end {
return
}

mid := (start + end) / 2
mergeSort(arr, start, mid)
mergeSort(arr, mid+1, end)
merge(arr, start, mid, end)
}

func merge(arr []int, start, mid, end int) {
tmpArr := make([]int, end-start+1)

i := start
j := mid + 1
k := 0
for ; i <= mid && j <= end; k++ {
if arr[i] < arr[j] {
tmpArr[k] = arr[i]
i++
} else {
tmpArr[k] = arr[j]
j++
}
}

for ; i <= mid; i++ {
tmpArr[k] = arr[i]
k++
}
for ; j <= end; j++ {
tmpArr[k] = arr[j]
k++
}
copy(arr[start:end+1], tmpArr)
}
12 changes: 12 additions & 0 deletions go/12_sorts/MergeSort_test.go
Original file line number Diff line number Diff line change
@@ -1 +1,13 @@
package _2_sorts

import "testing"

func TestMergeSort(t *testing.T) {
arr := []int{5, 4}
MergeSort(arr)
t.Log(arr)

arr = []int{5, 4, 3, 2, 1}
MergeSort(arr)
t.Log(arr)
}
37 changes: 37 additions & 0 deletions go/12_sorts/QuickSort.go
Original file line number Diff line number Diff line change
@@ -1 +1,38 @@
package _2_sorts

func QuickSort(arr []int) {
arrLen := len(arr)
if arrLen <= 1 {
return
}
quickSort(arr, 0, arrLen-1)
}

func quickSort(arr []int, start, end int) {
if start >= end {
return
}

pivot := partition(arr, start, end)
quickSort(arr, start, pivot)
quickSort(arr, pivot+1, end)
}

func partition(arr []int, low, high int) int {
pivotV := arr[low]
for low < high {
for low < high && arr[high] > pivotV { //指针从右边开始向右找到一个比pivot小的数
high--
}
arr[low] = arr[high] //将这个数放到low位,注意第一次这个位置放的是pivot值,所以不会丢

for low < high && arr[low] < pivotV { //指针从左边开始向右找到第一个比pivot大的数
low++
}
arr[high] = arr[low] //将这个数赋值给之前的high指针,因为之前high指针指向的数已经被一定,所以不会丢
}

//最后将pivot的值放入合适位置,此时low与high相等
arr[low] = pivotV
return low
}
12 changes: 12 additions & 0 deletions go/12_sorts/QuickSort_test.go
Original file line number Diff line number Diff line change
@@ -1 +1,13 @@
package _2_sorts

import "testing"

func TestQuickSort(t *testing.T) {
arr := []int{5, 4}
QuickSort(arr)
t.Log(arr)

arr = []int{5, 4, 3, 2, 1}
QuickSort(arr)
t.Log(arr)
}

0 comments on commit 58e8ec4

Please sign in to comment.