Menu
CoddyTech

排序与并列

Coddy 面向 C 开发者的 R 语言课程 课程的第 19 课,共 48 课。

C 的 qsort 会使用比较器原地修改提供的存储空间;要保留记录,必须对整个记录进行排序,或使用共享索引数组。R 的 order 会返回一个排列,而 sort 会返回排序后的值。对数据框的所有列应用同一个排列,才能保留行之间的对应关系;如果确定性输出取决于排序依据,还要指定用于打破平局的键。

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int by_length(const void *a,const void *b){const char *left=*(const char *const *)a;const char *right=*(const char *const *)b;size_t x=strlen(left),y=strlen(right);return x<y?-1:x>y?1:strcmp(left,right);}

int main(void){
const char *words[]={"pear","a","tea"};qsort(words,3,sizeof words[0],by_length);printf("%s,%s,%s\n",words[0],words[1],words[2]);
return 0;
}

R

words <- c("pear", "a", "tea")
cat(paste(words[order(nchar(words))], collapse=","), "\n", sep="")

索引的排列并不是排序后的值向量。

challenge icon

挑战

简单

返回按绝对值排序的输入数字;如果绝对值相同,则按实际数值升序排列。保留重复项。

保留已声明的公共 API。锁定的可见驱动程序会直接检查它,同时也会打印 solve(lines)。输入符合所述约定;所有算术运算的数值都很小且有限。

你的代码写在 Functions.R 和 Exercise.R 中。main.R 会按顺序加载依赖项,并包含提供的输入输出代码;不能编辑它。

亲手试试

source("Functions.R")
source("Exercise.R")
stopifnot(identical(compute(c(4,-4,2,-2)),c(-2,2,-4,4)))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C 开发者的 R 语言课程中的所有课

自己练习: R 在线编译器