用C中的第二个字段对结构数组进行排序

问题描述 投票:2回答:1

我的教授建议我们使用qsort()对一系列结构进行排序。但是,我必须发现它不稳定。我知道还有关于这个主题的其他帖子,但似乎都没有提供一个简单的解决方案来稳定我的排序。有没有办法让qsort()用于第二个数据字段?

这是我的代码:

#include <stdlib.h>
#include <stdio.h>

struct Map * collect_values(int n, int *arr);
void sort_values(struct Map *ptr, int n);
void print(struct Map *print_struct, int n);

struct Map{
    int value, position;
};

int compare(const void *aptr, const void *bptr){
    int a = ((struct Map*)aptr)->value, b = ((struct 
Map*)bptr)->value;
return (a > b) - (a < b);
}

int main(){
    int size, i;
    scanf("%d", &size);
    int *arr = (int*) malloc(size*sizeof(int));
    struct Map *p = collect_values(size,arr);
    qsort(p,size,sizeof(struct Map),compare);
    print(p,size);
    free(p);
    free(arr);
    return 0;
}

struct Map * collect_values(int n, int *arr){
    int i, position = 0;
    struct Map *array = calloc(n,sizeof(*array));
    for(i = 0; i < n; i++){
        scanf("%d",&arr[i]);
        array[i].value = arr[i];
        array[i].position = position;
        position++;
    }
    return array;

}

void print(struct Map * print_struct, int n){
    int i;
    for (i = 0; i < n; i++){
        printf("%d : %d\n", print_struct[i].value, 
print_struct[i].position);
    }
}

现在的输出是:

-3 : 3
1 : 9
3 : 2
4 : 8
4 : 1
5 : 5
5 : 4
7 : 6
25 : 0
88 : 7

如何维护重复的顺序?我花了很多时间试图找出qsort(),所以我想尽可能保留它。

编辑我不清楚我想要的输出。在排序之前,结构数组包含一个值和该值的索引。因此,原始的结构数组看起来像这样:

 25 : 0
  4 : 1
  3 : 2
 -3 : 3
  5 : 4
  5 : 5
  7 : 6
 88 : 7
  4 : 8
  1 : 9

排序后,我的代码打印了上面的内容。但是,我所希望的是这样的:

-3 : 3
1 : 9
3 : 2
4 : 1
4 : 8
5 : 4
5 : 5
7 : 6
25 : 0
88 : 7

如果第一个字段中的值相等,则需要按第二个字段中的值对它们进行排序,因为它们是索引,所以它们永远不会相等。

c qsort
1个回答
5
投票

由于该结构具有表示初始数组排序的position成员,因此您可以轻松地模拟稳定排序。在比较函数中,如果两个value成员相等,则返回基于position成员的排序,如下所示:

int compare(const void *ptr1, const void *ptr2)
{
    const struct Map *aptr = ptr1;
    const struct Map *bptr = ptr2;

    if (aptr->value == bptr->value)
        return (aptr->position > bptr->position) - (aptr->position < bptr->position);
    else
        return (aptr->value > bptr->value) - (aptr->value < bptr->value);
}
© www.soinside.com 2019 - 2024. All rights reserved.