繁体   English   中英

C语言中改进的qsort()函数

[英]An improved qsort() function in c

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

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

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

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

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

您可以做的是创建一个struct ,该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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM