如何使用循环对数据进行排序?

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

How to sort data by using loops?

问题

我想编写一个函数,可以按升序或降序重新排列一个向量。我知道可以使用sort和order函数来实现,但我想手动完成。

英文:

I want to write a function that rearranges a vector in ascending or descending order. I know I can use sort and order functions but I want to do it manually.

答案1

得分: 1

如果您想练习编写自己的排序函数,这里有一个应用了递归方法的示例:

mysort <- function(v, descending = FALSE) {
  if (length(v) == 1) return(v)
  if (descending) return(c(max(v), mysort(v[-which.max(v)], descending = descending))) 
  return(c(min(v), mysort(v[-which.min(v)])))
}

示例

v <- c(1, 2, 5, 4, 2, 7)
# 升序方式
mysort(v)
# 降序方式
mysort(v, descending = TRUE)

这样会得到以下结果:

> mysort(v)
[1] 1 2 2 4 5 7

> mysort(v, descending = TRUE)
[1] 7 5 4 2 2 1
英文:

If you want to practice writing your own sorting function, here is a example which applies a recursion approach:

mysort &lt;- function(v, descending = F) {
  if (length(v)==1) return(v)
  if (descending) return(c(max(v),mysort(v[-which.max(v)],descending = descending))) 
  return(c(min(v),mysort(v[-which.min(v)])))
}

EXAMPLE

v &lt;- c(1,2,5,4,2,7)
# ascending manner
mysort(v)
# descending manner
mysort(v,descending = T)

such that

&gt; mysort(v)
[1] 1 2 2 4 5 7

&gt; mysort(v,descending = T)
[1] 7 5 4 2 2 1

huangapple
  • 本文由 发表于 2020年1月3日 20:29:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/59578680.html
匿名

发表评论

匿名网友

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

确定