用QSORT在C中使用QSORT对索引进行最大值排序阵列
我需要对数组进行如下:
int *array = malloc(5 *sizeof(int))
假设array = [2,4,1,1,3,2]
index 0 1 2 3 4
我必须订购它具有最高值的索引是开始的,依此类推,以减少顺序
,因此输出必须为
array = [1,3,0,4,2]或[1,3,4,0,2](否很重要,因为索引0和4具有相同的值)
我知道我可以使用QSORT订购以进行价值来执行此操作:
int cmpfunc (const void * a, const void * b) {
return (*(int*)b - *(int*)a );
}
qsort(array, 5, sizeof(u32), cmpfunc);
但是该输出将是:
array = [4,3,2,2,1]
i need sort an array as follows:
int *array = malloc(5*sizeof(int))
Let's say array = [2, 4, 1, 3, 2]
index 0 1 2 3 4
I have to order it so that the index that has the highest value is at the beginning and so on in decreasing order
so the output has to be
array = [1 , 3, 0, 4, 2] or [1 , 3, 4, 0, 2] (no matters because index 0 and 4 have the same value)
I know that using qsort i can order for value doing this:
int cmpfunc (const void * a, const void * b) {
return (*(int*)b - *(int*)a );
}
qsort(array, 5, sizeof(u32), cmpfunc);
but the output of this one will be:
array = [4,3,2,2,1]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您要做的不是对值进行排序,而是对索引进行排序。
您从值数组开始,然后创建一个数组,其中值是当前索引号。
然后,在您的排序函数中,获得的值是原始数组中的索引。因此,然后使用这些值索引原始数组,然后比较这些值。
此示例使用固定的数组,但是将其调整很容易使用动态分配的数组。
输出:
What you want to do is not sort the values but sort the indices.
You start with the array of values, then create an array where the values are the current index number.
Then in your sorting function, the values you get are the indices into the original array. So then use those values to index the original array and then compare those values.
This example uses fixed arrays, but it's simple to adapt it to use dynamically allocated arrays.
Output: