【问题标题】:sort of arrays and their position数组的排序及其位置
【发布时间】:2012-03-07 17:51:14
【问题描述】:

我有一个排序问题。

我有两个数组

int a[] ={index1,index2,index3...indexI};
int b[] ={num1,num2,num3.......numI};

数组 b[] 具有随机顺序的数字,但它们的位置对应于 a[] 中的位置。 比如num1就是index1的值,num2就是index2的值。

问题是:

我需要对b[]元素进行降序排序,同时我需要根据b[]的排序顺序移动a[]元素的位置。

我可以使用其中一种排序算法按降序对 b[] 进行排序,但我无法根据 b[] 位置变化处理 a[] 元素的同时移动。 我期望的最终输出是在 b[] 中按其值的降序排列的 a[] 索引。

请帮忙。

谢谢

【问题讨论】:

  • 任何特定的语言?
  • 你能创建一个结构数组并对其进行排序吗?
  • @Chowlett 任何语言都可以:) 甚至逻辑或伪代码也可以。谢谢

标签: c arrays algorithm sorting


【解决方案1】:

如果我理解正确你想要这样的东西 a = [0 1 2]; b = [5 2 8] 和排序后 a = [1 0 2]; b = [2 5 8]。

当改变数字的位置时,你必须记住改变索引数组的排序算法:

例如。交换两个位置(伪代码)

swap(i, j): // i, j - indexes
   (b[i], b[j]) = (b[j], b[i]) // swap values
   (a[i], a[j]) = (a[j], a[i]) // swap the indexes

【讨论】:

    【解决方案2】:

    这显示了使用并行数组而不是结构数组的缺点之一。简单的解决方案是将您的代码转换为使用

     struct {int index, num;} a[] = {{index1, num1},{index2, num2}, ...};
    

    如果您的代码库已经大量使用并行数组,您可以编写一个意识到这些困难的排序。您可以向它传递一个数组数组,而不是单个数组,然后编写排序以在每个数组中执行交换,同时只对第一个数组执行比较。换句话说:

    void sort_pa(void **arrays/*NULL-terminated*/, int len,int size, int(*cmp)(...)))
    

    然后你会使用:

    int a[] ={index1,index2,index3...indexI};
    int b[] ={num1,num2,num3.......numI};
    int *c[] = {b, a, NULL};
    
    sort_pa(c, I, sizeof **c, cmp);
    

    【讨论】:

      【解决方案3】:

      使用 qsort,您将使用以下比较表达式对数组 a 进行排序:

      b[*(int*)elem1] - b[*(int*)elem2]
      

      其中 elem1 和 elem2 是比较器函数的两个指针参数(让 b 对函数可见)。

      这将使数组 b 保持不变,并且 b[a[i]] 将按降序给出 b 元素。

      【讨论】:

        【解决方案4】:

        您可以通过两种方式进行:首先,使用您最喜欢的排序算法对a 进行排序,但不要直接将a[i]a[j] 进行比较,而是将b[a[i]]b[a[j]] 进行比较。现在根据a 中的索引重新排列b - 就完成了。

        第二步可能如下所示(伪代码):

        var c = new int[b.length]
        for (int i = 0 ; i != a.length ; i++)
            c[i] = b[a[i]]
        b = c
        

        【讨论】:

          【解决方案5】:

          b 进行排序后,您可以通过比较函数对a 进行排序,该函数在b 中查找值。

          // assuming b is visible at the module level, you can pass this to qsort
          int compare_by_indexing_into_b(void const *a, void const *b)
          {
              int i = *(int const *)a;
              int j = *(int const *)b;
          
              return b[i] - b[j];
          }
          

          【讨论】:

            【解决方案6】:
            int a[] ={index1,index2,index3...indexI};
            int b[] ={num1,num2,num3.......numI};
            int c[] = {{num1, index1}, {num2, index2}...{indexI, numI}}
            sort(c);
            for i = 0 to c.len
              print c[i][1]
            

            在 c++ 中,我会使用成对向量。在其他语言中,您可以使用结构。

            【讨论】:

            • 我想在matlab中做。 Matlab无法对向量对进行排序!有什么建议吗?
            猜你喜欢
            • 2021-11-15
            • 1970-01-01
            • 2015-12-09
            • 1970-01-01
            • 2020-07-06
            • 2023-02-26
            • 1970-01-01
            • 1970-01-01
            • 2020-05-18
            相关资源
            最近更新 更多