编辑:这一切都是用 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 }
来表示对。你可以
- 编写一个函数来接受
numFields
和charFields
并返回一个pair
数组。 - 写一个比较函数,using this question and answers以供引用。其他 code examples here .
- 对你的数组对和你的比较函数调用
qsort
- 编写一个函数,将
pair
数组转换回charFields
。
关于c - 如何根据另一个数组的数字顺序对数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22761895/