我正在尝试实现一个快速排序算法,仅用于学习目的。
到目前为止,我已经提出了以下代码:
package main
import (
"fmt"
)
var arr = []int{20, 43, 52, -1, 43, 29, 34}
func main() {
fmt.Println("Unsorted: ", arr)
quick_sort(arr)
fmt.Println("Sorted: ", quick_sort(arr))
}
func quick_sort(arr []int) []int {
var recurse func(left int, right int)
var swap func(i int, j int)
var partition func(left int, right int, pivot int) int
swap = func(i int, j int) {
var temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
partition = func(left int, right int, pivot int) int {
v := arr[pivot]
right--
swap(pivot, right)
for i := left; i < right; i++ {
// arr[i] doesn't seem to be updating here
fmt.Println(arr, left, right, i, arr[i], v)
if arr[i] <= v {
left++
swap(i, left)
}
}
swap(left, right)
return left
}
recurse = func(left int, right int) {
if left < right {
pivot := (right + left) / 2
pivot = partition(left, right, pivot)
recurse(left, pivot)
recurse(pivot+1, right)
}
}
recurse(0, len(arr))
return arr
}
这是我之前用javascript编写的代码的直接翻译:
function quick_sort(arr) {
function partition(left, right, pivot) {
var v = arr[pivot];
swap(pivot, --right);
for (var i = left; i < right; i ++) {
console.log(arr, left, right, i, arr[i], v);
if (arr[i] <= v) {
swap(i, left++);
}
}
swap(left, right);
return left;
}
function swap(i, j) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
function recurse(left, right) {
if (left < right) {
var pivot = ~~((left + right) / 2)
pivot = partition(left, right, pivot);
recurse(left, pivot);
recurse(pivot + 1, right);
}
}
recurse(0, arr.length)
return arr;
}
var arr = [20, 43, 52, -1, 43, 29, 34];
console.log(quick_sort(arr));
它就像js中的魅力一样,但不知何故,我无法让它在go中工作。出于某种原因,在我的分区函数中,在我的for循环中,即使arr[i]
发生变化,i
的值也保持不变。
我花了很多时间试图弄清楚我做错了什么,但我无法弄清楚。
有没有人看到我失踪的东西?
答案 0 :(得分:6)
left++
应该在swap()
函数之后
if arr[i] <= v {
swap(i, left)
left++
}
修复后,输出
Unsorted: [20 43 52 -1 43 29 34]
Sorted: [-1 20 29 34 43 43 52]