← 都来码 / Dolaima← 例程索引r/school/insertion_sort.r 原文

r/school/insertion_sort.r · 782 字节 · 下载原文

# insertion_sort.r
# 来源 / Source: https://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
# 许可 / License: Rosetta Code 内容按 GNU FDL 1.3 发布(页面未另标许可)
# 说明 / Note: 整段照抄 / copied verbatim (loop + scalar, no vectorized builtins)
# ─────────────────────────────────────────────────────────────
insertionsort <- function(x)
{
   for(i in 2:(length(x)))
   {
      value <- x[i]
      j <- i - 1
      while(j >= 1 && x[j] > value)
      {
         x[j+1] <- x[j]
         j <- j-1
      }
      x[j+1] <- value
   }
   x
} 
insertionsort(c(4, 65, 2, -31, 0, 99, 83, 782, 1)) # -31   0   1   2   4  65  83  99 782