【问题标题】:How to sort the rows of a 2D Matrix using qsort?如何使用 qsort 对 2D 矩阵的行进行排序?
【发布时间】:2018-04-11 12:43:48
【问题描述】:

我的许多同事问我是否可以通过使用 <stdlib.h> 中的函数 qsort() 来排列矩阵,例如:

5, 8, 7, 6, 1, 4, 3, 2, 11、12、10、9、

变成类似:

5, 6, 7, 8, 1, 2, 3, 4, 9、10、11、12、

【问题讨论】:

  • 当然,“二维数组”中的一行只是一个一维数组。您可以像对任何其他数组一样对每一行进行排序。
  • @Code-Apprentice 不完全是,这个问题是关于指针数组的......但我仍然不完全明白这一点。
  • @FelixPalmen 这个问题没有给出二维数组的确切类型的任何声明。并且提议的解决方案没有说明任何关于指针的内容。
  • @Code-Apprentice 嗯?这里的问题是关于二维数组,建议的解决方案显示了处理二维数组的代码。 “重复的候选者”是关于指针数组的。正如我所说,我不明白这里的意思,但这仍然不是(确切的)重复。

标签: c qsort


【解决方案1】:

问题的解决方法如下:

#include <stdio.h>   // scanf() printf()
#include <stdlib.h>  // qsort()

int compare (const void *a, const void *b)
{
  int x = *(int *)a;
  int y = *(int *)b;

  if (x<y) return -1; 
  if (x>y) return 1; 
  return 0;
}

int main()
{
  // Syntax of a 2D Array: array[rows][cols]
  int rows = 3, cols = 4;
  int array[3][4] = { {5,8,7,6,}, {1,4,3,2}, {11,12,10,9} };

  // Print the matrix unsorted:
  printf("\nUnsorted rows:\n");
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      printf("%2d, ", array[i][j]);
    }
    printf("\n");
  }

  // Sort the matrix using qsort:
  for(int j = 0; j < rows; j++)
    qsort(array[j], cols, sizeof(int), compare);

  // Print the matrix sorted:
  printf("\nSorted rows:\n");
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      printf("%2d, ", array[i][j]);
    }
    printf("\n");
  }

  return 0;
}

输出

未排序的行: 5, 8, 7, 6, 1, 4, 3, 2, 11、12、10、9、 排序的行: 5, 6, 7, 8, 1, 2, 3, 4, 9、10、11、12、

感谢 flukey 提供的有用答案: Qsorting 2d pointer arrays

【讨论】:

  • 这个问题/答案比您链接的原版提供了什么?
  • compare 需要{ }
  • return ( *(int*)a - *(int*)b );
  • @PatrickSteiner 保持其可读性,执行int x = *(int *)a; int y = *(int *)b;,然后使用return (x&gt;y) - (x&lt;y); 或更冗长且更具可读性,结果相同if (x&lt;y) return -1; if (x&gt;y) return 1; return 0;
  • 你不应该在比较函数中抛弃const。从const void*int* 的转换没有明确定义。你应该得到编译器警告。改为转换为 const int*
【解决方案2】:

帕特里克,

将二维数组想象成许多一维数组的组合。

使用 2 个循环对每个 1d 数组(行)执行排序。一个循环遍历(列),一个循环遍历一维数组。在第二个内部循环中,您可以执行排序。

【讨论】:

  • 欢迎来到 Stack Overflow。既然要对每一行进行排序,为什么要对列进行迭代呢?你如何解释int array[3][4];——一个3行每行4列的数组,还是别的什么?你能概述你的代码吗?就目前而言,您的建议似乎偏离了目标。
猜你喜欢
  • 2014-06-05
  • 1970-01-01
  • 1970-01-01
  • 2015-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-15
  • 1970-01-01
相关资源
最近更新 更多