【问题标题】:An improved qsort() function in cc 中改进的 qsort() 函数
【发布时间】:2012-08-26 02:12:28
【问题描述】:

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

【问题讨论】:

  • 您可以手动完成,我的意思是在排序前后获取索引.. 对吗?
  • 你说的是posix'qsort(3)
  • @hroptatyr qsort() 是 C 标准库的一部分,POSIX 不会以任何方式改变其功能。
  • @Daniel 是的,我很困惑,因为 OP 正在谈论一个改进的版本,我打算提供一个具有不同签名的解决方案(这显然不是一个替代品)

标签: c sorting


【解决方案1】:

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

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);
}

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

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

【讨论】:

    【解决方案2】:

    你可以做的是创建一个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;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-08-17
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多