c - 使用 qsort 对数组结构进行排序

标签 c sorting

我有一个包含两个数组的结构:矩阵的行索引和列索引。这些索引没有顺序,我想使用 qsort 对它们进行排序。

我不想使用什么

我知道如果我有一个结构数组,这很容易。可能如下所示

// structure to store the row/column index
typedef struct Index {
  int row;
  int col;
} Index;

// function to compare two entries

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

    Index *Ia = (Index *) a;
    Index *Ib = (Index *) b;

    if(Ia->row  < Ib->row                      ) return -1;
    if(Ia->row == Ib->row && Ia->col  < Ib->col) return -1;
    if(Ia->row == Ib->row && Ia->col == Ib->col) return  0;
    if(Ia->row == Ib->row && Ia->col  > Ib->col) return  1;
    if(Ia->row  > Ib->row                      ) return  1;

}

// main program
int main(void) {

  int N = 3;
  Index mat[N];

  // fill the matrix with fictitious data
  mat[0].row = 1;   mat[0].col = 3;
  mat[1].row = 0;   mat[0].col = 2;
  mat[2].row = 0;   mat[0].col = 1;

  // sort the "matrix": first ascending rows, then ascending columns
  qsort(mat,N,sizeof(Index),cmp);

  return 0;

}

我想用什么

我的程序的构造使得我没有结构数组,但我有数组结构:

// define structure
typedef struct Matrix {
  int* row; 
  int* col; 
} Matrix;

// main program
int main(void) {

  // define fictitious data
  int row[3] = { 1 , 1 , 0 };
  int col[3] = { 3 , 2 , 1 };

  // define matrix
  Sparse mat;
  mat.row = row;
  mat.col = col;

  // sort
  // ...?


  return 0;

}

我想对行/列索引进行排序,如上所示。到目前为止,我将数据复制到结构数组中,进行排序,然后复制回来。但是,我使用的数据集太大,我想避免这种情况。

谢谢!

最佳答案

不是答案,而是对您在 qsort() 中使用 compare() 函数的方式的评论。这样效率会更高。

int cmp(const void *a, const void *b){
    Index *Ia = (Index *) a;
    Index *Ib = (Index *) b;

    if(Ia->row < Ib->row) return -1;
    if(Ia->row > Ib->row) return  1;
    if(Ia->col < Ib->col) return -1;
    if(Ia->col > Ib->col) return  1;
    return  0;
}

关于c - 使用 qsort 对数组结构进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28004565/

相关文章:

c - 奇怪的#define 声明,无法理解它扩展的内容

c - 循环条件问题 - 文件结尾

c++ - 将数据输入结构并对其进行排序

java - 如何按对象特定变量的字母顺序将对象添加到数组列表

javascript - 在javascript中对数组对象进行排序

c - Linux 中检测硬件断点

c - 交换字符指针

c - realloc 导致释放对象的校验和不正确

ios - 按 NSNumber 值对 NSDictionary 键进行排序

git - 相当于 PowerShell 中的 bash 排序