【问题标题】:Sort array in c在c中排序数组
【发布时间】:2012-11-23 12:58:27
【问题描述】:

我有一个结构数组。让我们称之为structsarray

我有一个整数数组,其中整数是结构的索引。让我们称之为indexarray

我想对indexarray 进行排序,但我想将排序与structsarray 中的int 进行比较

该设置有什么方法可以完成吗?

【问题讨论】:

标签: c qsort


【解决方案1】:

你有这样的比较函数:

int my_compare(const void *a, const void *b)
{
    int index1 = *((const int *) a);
    int indexb = *((const int *) b);

    return structsarray[index1].field - structsarray[index2].field;
}

参数是指向要排序的数组中的值的指针。我将常量 void 指针转换为常量 int 指针,然后取消引用该指针以获取实际值。

【讨论】:

  • 但我能以某种方式将指向structsarray 的指针作为参数传递吗?
  • @Razcou 如果您将structsarray 传递给qsort,则比较函数将获得两个指向该结构的指针,因此您必须执行例如struct my_struct *struct1 = (struct my_struct *) a;
【解决方案2】:

您可以通过实现自己的比较功能来使用 qsort。这里解释一下:http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/

【讨论】:

    【解决方案3】:

    提供的信息非常有限。 也许你可以这样做:

    算法示例: 冒泡排序:

      for (c = 0 ; c < ( n - 1 ); c++)
      {
        for (d = 0 ; d < n - c - 1; d++)
        {
          if (index[d] > index[d+1]) /* For decreasing order use < */
          {
    
            /* Sort index */
            swap       = index[d];
            index[d]   = index[d+1];
            index[d+1] = swap;
    
            /* Sort struct using above index */
            swap       = struct[d];
            struct[d]   = struct[d+1];
            struct[d+1] = swap;
    
          }
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2013-09-25
      • 2021-12-26
      • 2013-12-14
      • 1970-01-01
      • 1970-01-01
      • 2011-04-23
      • 2013-12-24
      • 2013-08-05
      相关资源
      最近更新 更多