C语言如何对数组进行排序但保留重复元素的位置?

How to Sort Array But Keep The Position of Duplicate Element in C?

所以,实际上我需要的是在排序后保留旧数组的索引。因此,例如,如果我输入 [2,4,1,5,7,9,6],则输出为 [2,0,1,3,6,4,5]。我已经使用了 qsort,如果没有重复元素,它工作得很好。

如果有重复的元素,有时第一个重复的元素被放在最后。比如输入是[5,4,6,5,2,1,3],我要输出的是[5,4,6,1,0,3,2]。因此,将索引 05 放在索引 35 之前。但是,使用 qsort 有时会使输出 [5,4,6,1,3,0,2].

你能帮我解决这个问题吗?还是我应该创建自己的排序功能?你能帮我创建它吗?

这是我的代码:

#include <stdlib.h>

int* sortidx(double *X,int n)
{
    int *idx,i,j;

    int cmp(const void *a,const void *b)
    {
        return X[*(int*)a]>=X[*(int*)b]?1:-1;
    }

    idx=(int*)calloc(n,sizeof(int));

    for(i=0;i<n;i++)
    {
        idx[i]=i;
    }

    qsort(idx,n,sizeof(int),cmp);

    return idx;
}

你要找的是 stable sorting algorithm. You can stabilize qsort in C, but it needs extra work. In C++ std::stable_sort 存在。

如果您需要坚持使用 C,那么您应该实现自己的稳定排序。这里有一个list的稳定排序算法:

B
Block sort
Bubble sort
Bucket sort
C
Cascade merge sort
Cocktail shaker sort
Counting sort
Cubesort
G
Gnome sort
I
Insertion sort
L
Library sort
M
Merge sort
O
Odd–even sort
Oscillating merge sort
P
Pigeonhole sort
Proxmap sort
R
Radix sort
T
Timsort

您希望一个元素被认为大于另一个元素,如果它的值更大或者如果值相等并且它的索引更大。 (这是稳定排序算法背后的思想。)

在这种情况下,您知道被比较元素的索引,因此您可以轻松地将其添加到您的比较标准中:

int cmp(const void *a, const void *b)
{
    return X[*(int*)a] > X[*(int*)b] ||
           (X[*(int*)a] == X[*(int*)b] && *(int*)a > *(int*)b)
           ?1:-1;
}

或者,可能更具可读性和迂腐的正确性(因为没有记录 ab 保证不同):

int cmp(const void *a, const void *b)
{
    int idxa = *(const int*)a, idxb = *(const int*)b;
    if (X[idxa] > X[idxb]) return 1;
    if (X[idxa] < X[idxb]) return -1;
    return idxa - idxb;
}

引用参数 X 的嵌套函数的使用是 gcc 扩展,可能不适用于其他编译器。标准 C 库的 Gnu 实现还包含函数 qsort_r,可用于将 X 传递给比较例程,但编写该函数的更可移植的方法是使用数组指针而不是索引数组:

int idxcmp(const void *a,const void *b)
{
    double *ap = *(double *const*)a, *bp = *(double *const*)b;
    if (*ap > *bp) return 1;
    if (*ap < *bp) return -1;
    return ap - bp; 
}

double** sortidx(double *X, size_t n)
{
    double **idx = calloc(n, sizeof(double*));
    for (size_t i=0; i<n; ++i) idx[i] = X + i;
    qsort(idx, n, sizeof(idx[0]), idxcmp);
    return idx;
}

(如果你真的想要return索引,你可以在return之前将指针转换为索引。)