【问题标题】:C - Sort float array while keeping track of indicesC - 在跟踪索引的同时对浮点数组进行排序
【发布时间】:2016-08-11 08:59:21
【问题描述】:

我有一个包含 3 个浮点值的数组:

float norms[3];

norms[0] = 0.4;
norms[1] = 3.2;
norms[2] = 1.7;

我想按降序对这个数组进行排序同时跟踪数组中值的原始索引

换句话说,给定数组norms[] = {0.4, 3.2, 1.7}和对应的索引{0, 1, 2},我基本上想获得一个对应ints的数组,它反映norms[]float值在降序后的原始位置种类。在这种情况下,它将是{1, 2, 0}

实现这一目标的最佳/最干净的方法是什么?

【问题讨论】:

  • 创建一个包含索引的大小相同的 int 类型数组。对浮点数组进行排序时,只需镜像 int 数组上的任何交换操作。
  • 使用带有索引字段的结构体,在排序前写下每个元素的索引,这样会保留数组中的原始位置。
  • @Lundin 无法实现问题的要求
  • @Lundin 究竟会实现什么?您的“解决方案”在哪里创建原始发布者想要的索引?您最终会得到一个已排序和未排序的数组,但您没有两者之间的索引,如果没有“思维混乱、未成熟的优化算法”,就无法获得它。
  • @DimitarSlavchev 我会让删除了您所指的任何 4 年前评论的版主来回答这个问题。

标签: c arrays sorting


【解决方案1】:

只需使用任何排序算法“别名”原始数组访问。冒泡排序示例

int len = 3;
bool switched = false;

float myFloatArr[3];
int myFloatIndex[3] = {0, 1, 2};

do
{
    switched = false;
    for(i = 1; i < len; i++)
    {
        if(myFloatArr[myFloatIndex[i - 1]] < myFloatArr[myFloatIndex[i]])
        {
            int temp = myFloatIndex[i];
            myFloatIndex[i] = myFloatIndex[i - 1];
            myFloatIndex[i - 1] = temp;
            switched = true;
        }
    }
}
while(switched);

【讨论】:

    【解决方案2】:

    使用结构存储值和索引,然后根据值排序。

    struct str
    {
        float value;
        int index;
    };
    
    int cmp(const void *a, const void *b)
    {
        struct str *a1 = (struct str *)a;
        struct str *a2 = (struct str *)b;
        if ((*a1).value > (*a2).value)
            return -1;
        else if ((*a1).value < (*a2).value)
            return 1;
        else
            return 0;
    }
    
    int main()
    {
        float arr[3] = {0.4, 3.12, 1.7};
        struct str objects[3];
        for (int i = 0; i < 3; i++)
        {
            objects[i].value = arr[i];
            objects[i].index = i;
        }
        //sort objects array according to value maybe using qsort
        qsort(objects, 3, sizeof(objects[0]), cmp);
        for (int i = 0; i < 3; i++)
            printf("%d ", objects[i].index); //will give 1 2 0
        // your code goes here
        return 0;
    }
    
    

    【讨论】:

      【解决方案3】:

      我能想到的最简洁的方法是创建一个包含浮点数和索引的结构。

      typedef struct str {
      float val;
      int index;
      } str;
      

      然后创建一个这个结构的数组,按照val排序。

      【讨论】:

      • 我们怎样才能做到这一点?请提供更完整的示例。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-28
      • 2021-08-16
      • 2013-06-28
      • 1970-01-01
      • 2010-12-07
      相关资源
      最近更新 更多