本文介绍了用C排序二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数组:

[105][2500]
[110][1800]
[105][800]
[105][1300]
[110][1200]
...

和我需要这样的:

[105][800]
[105][1300]
[105][2500]
[110][1200]
[110][1800]
...

新的编辑:这是我的code现在:
行是行nuber,阵列是二维int数组[行] [2]

NEW That's my code now:row is nuber of rows, array is that 2D int array[row][2]

 ...
 for (i = 0; i < row; i++)
    printf("(%d, %d)\n", array[i][0], array[i][1]);

 qsort(array, row, 2*sizeof(int), compare);

 printf("\n sorted: \n");
 for (i = 0; i < row; i++)
    printf("(%d, %d)\n", array[i][0], array[i][1]);
 ...

比较功能:

int compare(void const *p_lhs, void const *p_rhs) {
  int const *lhs = (int const *) p_lhs;
  int const *rhs = (int const *) p_rhs;

//  printf("%d %d  - %d %d", lhs[0], rhs[0], lhs[1], rhs[1]);
  if(lhs[0] < rhs[0]) return -1;
  if(lhs[0] > rhs[0]) return  1;
  if(lhs[1] < rhs[1]) return -1;
  if(lhs[1] > rhs[1]) return  1;

  return 0;
}

与比较功能pritf输出:

推荐答案

令人高兴的是,有的qsort 为标准库。真的所有您需要做的是外数组的元素提供一个比较函数。例如:

Happily, there's qsort for that in the standard library. Really all you have to do is provide a comparison function for elements of the outer array. For example:

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

// lexicographical comparison.
// Returns -1 for lhs < rhs, 1 for lhs > rhs, 0 for lhs == rhs.
int compare_line(void const *p_lhs, void const *p_rhs) {
  // These point to the elements of the outer arrays (that is,
  // they point to the inner arrays)
  double const *lhs = (double const *) p_lhs;
  double const *rhs = (double const *) p_rhs;

  if(lhs[0] < rhs[0]) return -1;
  if(lhs[0] > rhs[0]) return  1;
  if(lhs[1] < rhs[1]) return -1;
  if(lhs[1] > rhs[1]) return  1;

  return 0;
}

#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof*(arr))

int main(void) {
  double data[][2] = {
    { 105,  800 },
    { 105, 1300 },
    { 105, 2500 },
    { 110, 1200 },
    { 110, 1800 }
  };

  // Sorting here.
  qsort(data, ARRAY_SIZE(data), sizeof(data[0]), compare_line);

  for(size_t i = 0; i < ARRAY_SIZE(data); ++i) {
    printf("%lf %lf\n", data[i][0], data[i][1]);
  }
}

这篇关于用C排序二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 17:18
查看更多