用C进行数组排序 [英] Array sorting in C

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

问题描述

我不是C专家,并且已经阅读了该论坛的内容,但是我仍然需要一些有关C排序问题的建议.

I'm not C expert and I've read through the forum, but I still need some advice regarding a sorting problem on C.

我在C中有4个双精度的动态数组.它们的大小都相同,可以说n.我想做的是使用一个数组作为一阶并将第二个数组作为我的二阶来对它们进行排序.因此,如果数组是* x,* y,* w和* z.我想根据* x的值对它们进行排序,然后按照* y的值对它们进行排序.

I have 4 dynamic arrays of doubles in C. All of them are the same size, and lets say n. What I want to do is to sort all of them using one of the arrays as first order and a second array as my second order. So if the arrays are *x, *y, *w and *z. I want to sort them according to the values of *x, then *y.

我必须有效地执行此操作,因为数组很大.

I must do this efficiently because the arrays are quite large.

任何帮助将不胜感激.

Any help will be much appreciated.

推荐答案

简单的 方法是将四个单独的数组映射到struct类型的单个数组上,例如

The easy way to do this would be to map your four separate arrays onto a single array of a struct type like

struct rec {
  double x;
  double y;
  double w;
  double z;
};

struct rec *arr = malloc( sizeof *arr * N ); // where N is the number of
                                             // elements in each array

if ( !arr )
  // malloc failed, handle error somehow

for ( size_t i = 0; i < N; i++ )
{
  arr[i].x = x[i];
  arr[i].y = y[i];
  arr[i].w = w[i];
  arr[i].z = z[i];
}

,然后创建一个比较函数以传递给qsort:

and then create a comparison function to pass to qsort:

int cmpRec( const void *lhs, const void *rhs )
{
  struct rec *l = lhs;
  struct rec *r = rhs;

  if ( l->x < r->x )
    return -1;
  else if ( l->x > r->x )
    return 1;
  else
  {
    if ( l->y < r->y )
      return -1;
    else if ( l->y > r->y )
      return 1;
    else
      return 0;
  }

  return 0;
}

现在,您可以使用qsort库函数对该结构数组进行排序:

Now you can use the qsort library function to sort that array of struct:

qsort( arr, N, sizeof *arr, cmpRec );

对数组进行排序后,您可以将结果映射回四个原始数组.

Once that array is sorted, you can map the results back onto your four original arrays.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆