用QSORT在C中使用QSORT对索引进行最大值排序阵列

发布于 2025-02-01 17:44:01 字数 521 浏览 2 评论 0原文

我需要对数组进行如下:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

羁拥 2025-02-08 17:44:01

您要做的不是对值进行排序,而是对索引进行排序。

您从值数组开始,然后创建一个数组,其中值是当前索引号。

然后,在您的排序函数中,获得的值是原始数组中的索引。因此,然后使用这些值索引原始数组,然后比较这些值。

int order[] = {2, 4, 1, 3, 2};

int cmp(const void *p1, const void *p2)
{
    const int *a = p1, *b = p2;
    return order[*b] - order[*a];
}

int main()
{
    int idx[] = {0,1,2,3,4};
    qsort(idx,5,sizeof(int), cmp);
    int i;
    for (i=0;i<5;i++) {
        printf("%d\n", idx[i]);
    }
    return 0;
}

此示例使用固定的数组,但是将其调整很容易使用动态分配的数组。

输出:

1
3
0
4
2

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.

int order[] = {2, 4, 1, 3, 2};

int cmp(const void *p1, const void *p2)
{
    const int *a = p1, *b = p2;
    return order[*b] - order[*a];
}

int main()
{
    int idx[] = {0,1,2,3,4};
    qsort(idx,5,sizeof(int), cmp);
    int i;
    for (i=0;i<5;i++) {
        printf("%d\n", idx[i]);
    }
    return 0;
}

This example uses fixed arrays, but it's simple to adapt it to use dynamically allocated arrays.

Output:

1
3
0
4
2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文