主页

go算法入门(身高的排序:从低到高)

2023-03-30 05:48PM

题目:

输入:names = ["Mary","John","Emma"], heights = [180,165,170]

输出:["John","Emma","Mary"]

解释:Mary 最高,接着是 Emma 和 John

代码如下:

package main
import "fmt"
//把名字按照身高排序(由低到高)输出结果
func sort_people(name []string, height []int)[]string{
  for n := 0; n < len(name); n++{
    for  h := 0; h < len(height); h++{
      if height[n] < height[h]{
        height[n], height[h] = height[h], height[n]
        name[n], name[h] = name[h], name[n] 
      }
    }
  }
  return name
}
func main() {
  name := []string{"Mary", "John", "Emma"}
  height := []int{180,165,170}
  fmt.Println(sort_people(name, height))
}

结果:

[John Emma Mary]

返回>>

登录

请登录后再发表评论。

评论列表:

目前还没有人发表评论