gpt4 book ai didi

sorting - 为什么在使用递归函数时更新我的​​(初始)变量?

转载 作者:行者123 更新时间:2023-12-01 22:42:29 24 4
gpt4 key购买 nike

我决定在go中创建快速排序算法。

我的快速排序代码是:

package sorting

func QuickSort(input []int) []int {

if len(input) <= 1 {
return input
}

sorted := input
pivotIndx := len(sorted) - 1 // The index of the last item of the array
pivot := sorted[pivotIndx] // The value of the last item in the array
curLowIndx := 0

for indx, val := range sorted {
if val < pivot {
// Swap the items
sorted[indx], sorted[curLowIndx] = sorted[curLowIndx], sorted[indx]
// Increment the index on which the low position is stored.
// We need to do this so that the next item that is lower can be stored/swapped with the correct position
curLowIndx = curLowIndx + 1
}
}

sorted[curLowIndx], sorted[pivotIndx] = sorted[pivotIndx], sorted[curLowIndx]

// Sort the sub-arrays
QuickSort(sorted[:curLowIndx])
QuickSort(sorted[curLowIndx+1:])

return sorted

}


主文件的代码:

package main

import (
"fmt"

"github.com/.../.../sorting"
)

func main() {

// Sorting examples
toSort := []int{100, 20, 70, 30, 90, 40, 120, 123, 10, 23}

fmt.Println(toSort) // returns: [100 20 70 30 90 40 120 123 10 23]
shouldBeSorted := sorting.QuickSort(toSort)
fmt.Println(shouldBeSorted) // returns: [10 20 23 30 40 70 90 100 120 123]
fmt.Println(toSort) // ALSO returns: [10 20 23 30 40 70 90 100 120 123]

}


在我的主要功能中,我在要排序的变量中有一个 slice ( toSort)。
我创建一个新变量,要在其中存储排序后的 slice ( shouldBeSorted)。
但是在这里,我发现了一些意料之外的东西。
当我调用 sorting.QuickSort(toSort)时,它会对其进行排序,并将返回值分配给 shouldBeSorted变量,但除此之外,它还会使用 toSort的结果更新 sorting.QuickSort(toSort)变量。

我已经阅读了go中指针的用法,希望在传递指针时会出现这种行为,但在传递“regular”变量时却不会。

所以我的实际问题是:为什么会这样?为什么要更改 toSort变量?我做错了什么吗?还是这是预期的?为什么会这样?

边注:
递归发生时,它本身也会在QuickSort函数中发生相同的事情:

QuickSort(sorted[:curLowIndx])
QuickSort(sorted[curLowIndx+1:])

虽然我首先需要将要返回的 slice 组合在一起,但是显然它会更新原始排序的 slice 。

最佳答案

go中的 slice 实际上由具有元信息的结构和指向存储实际数据的连续内存位置的指针组成。即使您通过值传递toSort,复制的meta结构仍然引用相同的基础内存位置。这就是toSort也被更改的原因。

如果您不希望发生这种情况,则可以使用copy创建一个新的 slice 并将其继续。

slice 内部:https://blog.golang.org/slices-intro

复制:https://golang.org/pkg/builtin/#copy

关于sorting - 为什么在使用递归函数时更新我的​​(初始)变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61891022/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com