Skip to content

Commit

Permalink
Merge pull request wangzheng0822#235 from swnb/fixbug-golang-quicksort
Browse files Browse the repository at this point in the history
Fixbug golang quicksort
  • Loading branch information
wangzheng0822 authored Jan 17, 2019
2 parents 86e9037 + 2b8b907 commit 488f6a7
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 25 deletions.
43 changes: 20 additions & 23 deletions go/12_sorts/QuickSort.go
Original file line number Diff line number Diff line change
@@ -1,38 +1,35 @@
package _2_sorts

// QuickSort is quicksort methods for golang
func QuickSort(arr []int) {
arrLen := len(arr)
if arrLen <= 1 {
return
}
quickSort(arr, 0, arrLen-1)
separateSort(arr, 0, len(arr)-1)
}

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

pivot := partition(arr, start, end)
quickSort(arr, start, pivot)
quickSort(arr, pivot+1, end)
i := partition(arr, start, end)
separateSort(arr, start, i-1)
separateSort(arr, i+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值,所以不会丢
func partition(arr []int, start, end int) int {
// 选取最后一位当对比数字
pivot := arr[end]

for low < high && arr[low] < pivotV { //指针从左边开始向右找到第一个比pivot大的数
low++
var i = start
for j := start; j < end; j++ {
if arr[j] < pivot {
if !(i == j) {
// 交换位置
arr[i], arr[j] = arr[j], arr[i]
}
i++
}
arr[high] = arr[low] //将这个数赋值给之前的high指针,因为之前high指针指向的数已经被一定,所以不会丢
}

//最后将pivot的值放入合适位置,此时low与high相等
arr[low] = pivotV
return low
arr[i], arr[end] = arr[end], arr[i]

return i
}
15 changes: 13 additions & 2 deletions go/12_sorts/QuickSort_test.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
package _2_sorts

import "testing"
import (
"math/rand"
"testing"
)

func createRandomArr(length int) []int {
arr := make([]int, length, length)
for i := 0; i < length; i++ {
arr[i] = rand.Intn(100)
}
return arr
}

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

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

0 comments on commit 488f6a7

Please sign in to comment.