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

use*_*424 2 c qsort

我的教授建议我们用它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);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在的输出是:

-3 : 3
1 : 9
3 : 2
4 : 8
4 : 1
5 : 5
5 : 4
7 : 6
25 : 0
88 : 7
Run Code Online (Sandbox Code Playgroud)

如何维护重复的顺序?我花了很多时间试图搞清楚qsort(),所以如果可能的话,我想保留它.

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

 25 : 0
  4 : 1
  3 : 2
 -3 : 3
  5 : 4
  5 : 5
  7 : 6
 88 : 7
  4 : 8
  1 : 9
Run Code Online (Sandbox Code Playgroud)

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

-3 : 3
1 : 9
3 : 2
4 : 1
4 : 8
5 : 4
5 : 5
7 : 6
25 : 0
88 : 7
Run Code Online (Sandbox Code Playgroud)

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

use*_*109 5

由于struct具有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);
}
Run Code Online (Sandbox Code Playgroud)