1

假设我们正在使用 qsort() 对一维数组进行排序,是否有一种简单的方法可以从排序数组的元素中检索该元素在排序之前在数组中被索引时的索引。假设 c[N] 排序为 d[N],如何从整数 i, j 中找到 c[j]=d[i] ?当我的意思是一种简单的方法时,qsort(带有一些附加参数)是否存储这种信息(排序后索引之间的双射)或者它是否存在可以轻松排序和检索这种信息的 qsort 改进函数?

4

2 回答 2

5

假设您使用如下结构填充初始数组:

struct IndexedInteger {
  int value;
  int index;
}

然后,您需要在循环中填充索引:

void addIndices(IndexedInteger * array, size_t num) {
  int i;
  for (i = 0; i < num; ++i) {
    array[i].index = i;
  }
}

然后你将对你的数组进行排序:

int compareIndexed(const void * elem1, const void * elem2) {
  IndexedInteger * i1, *i2;
  i1 = (IndexedInteger*)elem1;
  i2 = (IndexedInteger*)elem2;
  return i1->value - i2->value;
}

void sortArray(IndexedInteger * array, size_t num) {
  qsort(array, num, sizeof(IndexedInteger), compareIndexed);
}

然后,您将使用初始索引对数组进行排序。

免责声明:我写得很快,可能会有错误。

于 2012-08-31T09:26:20.773 回答
1

你可以做的是创建一个struct保存你的数据(在这种情况下,一个整数)和一个整数,它对应于它最初在你的数组上的位置的索引。澄清,

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

struct myData {
    int data;
    int orig_pos; // will hold the original position of data on your array
};

int myData_compare (const void* a, const void* b) {

    return ((struct myData*)a)->data - ((struct myData*)b)->data;
}

int main () {

    size_t N = 10; // size of your array
    struct myData* array = (struct myData*) malloc(N * sizeof(struct myData));
    for (size_t i = 0; i < N; i++) {
        array[i].data     = N - i; // array will hold 10,9,8,7,...1 in this order
        array[i].orig_pos = i;
    }
    qsort(array, N, sizeof(struct myData), &myData_compare);
    for (size_t i = 0; i < N; i++) {
        printf("\ndata: %d, orig_pos: %d", array[i].data, array[i].orig_pos);
    }
    return 0;
}
于 2012-08-31T09:41:40.323 回答