Quicksort in Go

huangapple go评论71阅读模式
英文:

Quicksort in Go

问题

我正在学习Go,并尝试实现快速排序算法,但是它没有返回完整的列表。根据我对Go的理解,它与我编写的一个正常工作的Ruby实现相匹配。

我的代码如下:

func quickSort(data []string) []string {
  if len(data) > 1 {
    pivot := data[0]
    smaller := make([]string, 0, len(data))
    equal := make([]string, 0, len(data))
    larger := make([]string, 0, len(data))
    for i := 1; i < len(data); i++ {
      if data[i] > pivot {
        larger = append(larger, data[i])
      } else if data[i] < pivot {
        smaller = append(smaller, data[i])
      } else {
        equal = append(equal, data[i])
      }
    }
    return append(append(quickSort(smaller), equal...), quickSort(larger)...)
  } else {
    return data
  }
}

我对其中的问题感到非常困惑。

英文:

I'm learning Go, and tried to implement a quicksort, however it doesn't return a complete list. To my understanding of Go it matches with a functioning Ruby implementation I wrote.

My code is:

func quickSort(data []string) []string {
  if len(data) &gt; 1 {
    pivot := data[0]
    smaller := make([]string, 0, len(data))
    equal := make([]string, 0, len(data))
    larger := make([]string, 0, len(data))
    for i := 1; i &lt; len(data); i++ {
      if data[i] &gt; pivot {
        larger = append(larger, data[i])
      } else if data[i] &lt; pivot {
        smaller = append(smaller, data[i])
      } else {
        equal = append(equal, data[i])
      }
    }
    return append(append(quickSort(smaller), equal...), quickSort(larger)...)
  } else {
    return data
  }
}

I am very puzzled as to what in this doesn't work.

答案1

得分: 6

你的问题是你从未将枢轴值附加到返回的切片中。因此,在每次递归调用中,你都会丢失枢轴。

对代码进行以下更改,它就会正常工作:

equal := make([]string, 1, len(data))
equal[0] = pivot
英文:

The bug you have is that you never append the pivot value to the returned slice. So for each recursive call, you will lose the pivot.

Make the following change to the code and it will work:

equal := make([]string, 1, len(data))
equal[0] = pivot

huangapple
  • 本文由 发表于 2014年6月30日 13:20:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/24483364.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定