// QuickSort project main.go
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
var my_slice = make([]int, 0, 100)
rand.Seed(int64(time.Now().Nanosecond()))
for i := 0; i < 10; i++ {
my_slice = append(my_slice, rand.Intn(1001))
}
fmt.Println("Before The Quick Sort:")
fmt.Println(my_slice)
fmt.Println("Sorting......")
QuickSort(my_slice, 0, len(my_slice)-1)
fmt.Println("OK! Finish!!!")
fmt.Println("After The Quick Sort:")
fmt.Println(my_slice)
}
func QuickSort(slice_arg []int, iLeft int, iRight int) {
var iIndex = (iLeft + iRight) / 2
var iTmpVal = slice_arg[iIndex]
i, j := iLeft, iRight
for i < j {
fmt.Println("i,j = ", i, j)
for i < iIndex && slice_arg[i] < slice_arg[iIndex] {
i++
}
if i < iIndex {
slice_arg[iIndex] = slice_arg[i]
iIndex = i
}
for j > iIndex && slice_arg[j] > slice_arg[iIndex] {
j--
}
if iIndex < j {
slice_arg[iIndex] = slice_arg[j]
iIndex = j
}
}
slice_arg[iIndex] = iTmpVal
if iIndex-iLeft > 1 {
QuickSort(slice_arg, iLeft, iIndex-1)
}
if iRight-iIndex > 1 {
QuickSort(slice_arg, iIndex+1, iRight)
}
}
更多评论
跟踪一下就知道为啥了。
另外,你的算法写的不对。
func QuickSort(slice_arg []int, iLeft int, iRight int) {
if iLeft < iRight {
var iTmpVal = slice_arg[iLeft]
var i, j = iLeft, iRight
for i < j {
fmt.Println("i,j = ", i, j)
for i < j && slice_arg[j] > iTmpVal {
j--
}
if i < j {
slice_arg[i] = slice_arg[j]
i++
}
for i < j && slice_arg[i] < iTmpVal {
i++
}
if i < j {
slice_arg[j] = slice_arg[i]
j--
}
}
slice_arg[i] = iTmpVal
QuickSort(slice_arg, iLeft, i-1)
QuickSort(slice_arg, j+1, iRight)
}
}
#2