This commit is contained in:
leotyliu(刘天一) 2018-10-17 15:56:58 +08:00
parent f4d518726b
commit 58e8ec469b
4 changed files with 108 additions and 0 deletions

View File

@ -1 +1,48 @@
package _2_sorts 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)
}

View File

@ -1 +1,13 @@
package _2_sorts 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)
}

View File

@ -1 +1,38 @@
package _2_sorts 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
}

View File

@ -1 +1,13 @@
package _2_sorts 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)
}