c - 如何根据另一个数组的数字顺序对数组进行排序?

标签 c sorting qsort

编辑:这一切都是用 C 语言完成的。

假设我有以下两个数组:

int numFields[] = {5, 1, 3, 2, 7}
char charFields[] = {'a' , 'b', 'c', 'd', 'e'}

我想对 numFields 进行数字排序,并使用 charFields 来匹配 numFields 的新顺序,这样:

int numFields[] = {1, 2, 3, 5, 7}
char charFields[] = {'b', 'd', 'c', 'a', 'e'}

我知道可以使用 qsort 对 numFields 进行数字排序,但是是否可以对 charFields 进行排序以匹配 numFields 的索引变化?是否有内置函数,还是我必须自己实现?

谢谢

最佳答案

qsort 可让您指定自己的比较函数,以指定应根据什么条件对数组进行排序。它允许您对任何类型的数组进行排序(可以是 int,可以是 struct),只要您知道要排序的对象的大小即可。你最好的选择是创建一个 struct pair { int numValue; char charValue } 来表示对。你可以

  1. 编写一个函数来接受 numFieldscharFields 并返回一个 pair 数组。
  2. 写一个比较函数,using this question and answers以供引用。其他 code examples here .
  3. 对你的数组对和你的比较函数调用qsort
  4. 编写一个函数,将 pair 数组转换回 charFields

关于c - 如何根据另一个数组的数字顺序对数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22761895/

相关文章:

c - 如何让 FFTW 在 Windows XP 上的 Eclipse CDT 中工作

c - 为什么 sbrk() 不告诉我正在使用多少堆?

c - Visual C++ 2010 Express 代码中的灰色(禁用)文本。这是什么意思?我该如何解决?

sorting - 集合排序

c++ - 必须使用 '.*' 或 '->*' 来调用 'lessThan (...)' 中的指向成员函数的指针,例如 '(... ->* lessThan) (...)'

c - UNIX shell C 管道的执行

sorting - 真的有人对 TB 级的数据进行排序吗?

Linux shell 和排序 -t 和 -k

c - 在指针数组的 qsort 实现中使用 FOR 循环但不使用 WHILE 时出现段错误

c - 我在 linux 中的 qsort 有什么问题?